现在,我必须将我的链接器设置为 "全部链接 "才能提交到App Store,因为UIWebView已经被废弃。在这样做的时候,我不得不添加 [Preserve(AllMembers = true)]
到我的DataStores中,使它们以这种方式工作,但后来我遇到了这个问题。
下面一行会返回null。
var dp = DependencyService.Get<ITextMeter>();
在研究了解决方案后,似乎最好的答案是在AppDelegate中添加以下一行。
DependencyService.Register<ITextMeter, TextMeterImplementation>();
一旦我这么做了,我就开始收到这个异常。
DependencyService: System.MissingMethodException: Default constructor not found for [Interface]
https:/forums.xamarin.comdiscussion71072dependencyservice-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);
}
}
TextMeterImplementation:
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;
}
}
}