在绘制点设置具有多种字体颜色的 UILabel



如何在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];

我希望有绿色字体的字符串 1 和红色字体的字符串 2

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

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;

最新更新