现在,由于UIWebView已弃用,我必须将链接器设置为"全部链接"才能提交到App Store。在执行此操作时,我不得不向我的数据存储添加[Preserve(AllMembers = true)]
以使它们以这种方式工作,但后来我遇到了这个问题。
以下行将返回空值:
var dp = DependencyService.Get<ITextMeter>();
在研究解决方案后,似乎最好的答案是将以下行添加到应用程序委托中:
DependencyService.Register<ITextMeter, TextMeterImplementation>();
一旦我这样做了,我就开始收到这个异常:
DependencyService: System.MissingMethodException: Default constructor not found for [Interface]
https://forums.xamarin.com/discussion/71072/dependencyservice-system-missingmethodexception-default-constructor-not-found-for-interface
我只想找到一个可行的解决方案,允许所有内容与设置为"全部链接"的链接器一起工作。提前谢谢。
ITextMeter:
using System;
using Xamarin.Forms.Internals;
namespace RedSwipe.Services
{
public interface ITextMeter
{
double MeasureTextSize(string text, double width, double fontSize, string fontName = null);
}
}
文本计量实现:
using System.Drawing;
using Foundation;
using RedSwipe.iOS.Services;
using RedSwipe.Services;
using UIKit;
[assembly: Xamarin.Forms.Dependency(typeof(TextMeterImplementation))]
namespace RedSwipe.iOS.Services
{
public class TextMeterImplementation : ITextMeter
{
public double MeasureTextSize(string text, double width, double fontSize, string fontName = null)
{
var nsText = new NSString(text);
var boundSize = new SizeF((float)width, float.MaxValue);
var options = NSStringDrawingOptions.UsesFontLeading | NSStringDrawingOptions.UsesLineFragmentOrigin;
if (fontName == null)
{
fontName = "HelveticaNeue";
}
var attributes = new UIStringAttributes
{
Font = UIFont.FromName(fontName, (float)fontSize)
};
var sizeF = nsText.GetBoundingRect(boundSize, options, attributes, null).Size;
//return new Xamarin.Forms.Size((double)sizeF.Width, (double)sizeF.Height);
return (double)sizeF.Height;
}
}
}
在类实现之前将此[Preserve (AllMembers = true)]
添加到TextMeterImplementation
中。
您的代码如下所示:
using System.Drawing;
using Foundation;
using RedSwipe.iOS.Services;
using RedSwipe.Services;
using UIKit;
using Xamarin.Forms.Internals; // Add This import
[assembly: Xamarin.Forms.Dependency(typeof(TextMeterImplementation))]
namespace RedSwipe.iOS.Services
{
[Preserve (AllMembers = true)]
public class TextMeterImplementation : ITextMeter
{
public double MeasureTextSize(string text, double width, double fontSize, string fontName = null)
{
var nsText = new NSString(text);
var boundSize = new SizeF((float)width, float.MaxValue);
var options = NSStringDrawingOptions.UsesFontLeading | NSStringDrawingOptions.UsesLineFragmentOrigin;
if (fontName == null)
{
fontName = "HelveticaNeue";
}
var attributes = new UIStringAttributes
{
Font = UIFont.FromName(fontName, (float)fontSize)
};
var sizeF = nsText.GetBoundingRect(boundSize, options, attributes, null).Size;
//return new Xamarin.Forms.Size((double)sizeF.Width, (double)sizeF.Height);
return (double)sizeF.Height;
}
}
}