【问题标题】:Setting UILabel with multiple font color at drawatpoint在 drawatpoint 处使用多种字体颜色设置 UILabel
【发布时间】:2019-10-21 07:48:24
【问题描述】:

如何在 UIlabel drawatpoint 中设置多种字体颜色。

我尝试使用下面的代码来更改字体属性,但我不知道如何将 NSMutableAttributedString 设置为此,因为它只接受 NSDictionary

[self.textColor setFill];
[self.text drawAtPoint:rect2.origin withAttributes:attrName];

我们用它来设置属性

NSMutableAttributedString *attrsString =  
[[NSMutableAttributedString alloc] 
initWithAttributedString:"String1/String2"];

// search for word occurrence
NSRange prange = [lbl.text rangeOfString:@"String1"];
NSRange lrange = [lbl.text rangeOfString:@"String2"];

if (prange.location != NSNotFound) {
     [attrsString addAttributes:attributeGreen range:prange];
     [attrsString addAttributes:attributeRed range:lrange];
}
lbl.attributedText = attrsString;

最初我们在 UILabel 子类中使用它 - 这个子类用于调整文本大小。

[self.textColor setFill];
[self.text drawAtPoint:rect2.origin withFont:tmpfont];

我希望 String1 为绿色字体,String 2 为红色字体

【问题讨论】:

标签: objective-c uilabel


【解决方案1】:

添加带有字体大小的字体属性。

NSString *string = @"String1/String2";

NSMutableAttributedString *attrsString =  
[[NSMutableAttributedString alloc] 
initWithAttributedString:@"String1/String2"];

// search for word occurrence
NSRange prange = [lbl.text rangeOfString:@"String1"];
NSRange lrange = [lbl.text rangeOfString:@"String2"];

//Setting font 
[attrString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, string.length)];

if (prange.location != NSNotFound) {
 [attrsString addAttribute: NSForegroundColorAttributeName value: [UIColor greenColor] range:prange];
}
if (lrange.location != NSNotFound) {
 [attrsString addAttribute: NSForegroundColorAttributeName value: [UIColor redColor] range:lrange];
}
lbl.attributedText = attrsString;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 2016-04-12
    • 2010-09-27
    相关资源
    最近更新 更多