OGeek|极客世界-中国程序员成长平台

标题: ios - 属性字符串 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:16
标题: ios - 属性字符串

a text that has some part with yellow background我需要在黄色文本的左侧和右侧进行一些填充,并且需要将标签“3”作为中心。我正在使用属性文本。任何人都可以帮我解决这个问题。下面是我正在使用的代码。附加截图为好吧。

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



Best Answer-推荐答案


恐怕唯一的解决方案是设置 offset(在 KerningAdjustment 上使用)具有适当的值。

对比

enter image description here

enter image description here

关于ios - 属性字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47247106/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://ogeek.cn/) Powered by Discuz! X3.4