归因于字符串

时间:2017-11-12 09:04:50

标签: ios xamarin.ios

a text that has some part with yellow background我需要在黄色文本的左右两侧填充一些填充,并且需要标签“3”作为中心。我正在使用属性文本。任何人都可以帮助我.Below是我正在使用的代码。同时附带截图。

string CardTileText = "3 Shared Documents";
NSAttributedString decoratedText = CardTileText.GetAttributedStringFromHtml("#ffe601","3");


  public static NSAttributedString GetAttributedStringFromHtml(this string source, UIColor color, string identifier)
        {
            var atts = new UIStringAttributes();
            UIFont newConnFont = UIFont.FromName("NotoSans-Bold", 16);
            NSRange range = GetRangeFor(source, identifier);
            NSNumber offset = 5;

            NSMutableParagraphStyle para = new NSMutableParagraphStyle
            {
                Alignment = UITextAlignment.Left
            };
            NSMutableAttributedString attributedString = new NSMutableAttributedString(source, atts);
            attributedString.AddAttribute(UIStringAttributeKey.BackgroundColor, color, range);
            attributedString.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.Black, range);
            attributedString.AddAttribute(UIStringAttributeKey.Font, newConnFont, range);
            attributedString.AddAttribute(UIStringAttributeKey.KerningAdjustment, offset, range);
            attributedString.AddAttribute(UIStringAttributeKey.ParagraphStyle, para, range);

            return attributedString;
        }

        static NSRange GetRangeFor(string source, string substring)
        {
            var range = new NSRange
            {
                Location = source.IndexOf(substring, StringComparison.Ordinal),
                Length = substring.Length
            };
            return range;
        }

1 个答案:

答案 0 :(得分:0)

我担心唯一的解决方案是使用适当的值设置offset(在KerningAdjustment上使用)。

这是比较

  • offset = 0.5

enter image description here

  • offset = 10

enter image description here