Xamarin bug happens when linker is set to “Link All”. Can't use DependencyService

帅比萌擦擦* 提交于 2020-06-17 03:42:11

问题


Right now, I have to have my linker set to "Link All" in order to submit to the App Store because of the deprecated UIWebView. While doing this, I had to add [Preserve(AllMembers = true)] to my DataStores to make them work this way, but then I ran into this issue.

The following line will return null:

var dp = DependencyService.Get<ITextMeter>();

After looking into the solution, it seemed the best answer would be to add the following line into the AppDelegate:

DependencyService.Register<ITextMeter, TextMeterImplementation>();

Once I did that, I started receiving this exception:

DependencyService: System.MissingMethodException: Default constructor not found for [Interface] https://forums.xamarin.com/discussion/71072/dependencyservice-system-missingmethodexception-default-constructor-not-found-for-interface

I just want to find a working solution that will allow everything to work with the linker set to "Link All". Thanks in advance.

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;
        }

    }
}

来源:https://stackoverflow.com/questions/61757404/xamarin-bug-happens-when-linker-is-set-to-link-all-cant-use-dependencyservic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!