我制作了自定义attributed label
,它适用于字母或数字字符。但是,当将文本更改为某个包含中文(或日文,韩文等)字符时,它将无法正常工作。
例如
我已初始化attributed label
,并使用enter code here
NSString *duesStr = @"150.00 元";
[attrLabel setText:duesStr];
[attrLabel setFont:[UIFont boldSystemFontOfSize:17] fromIndex:0 length:duesStr.length];
[attrLabel setColor:[UIColor redColor] fromIndex:0 length:6];
[attrLabel setColor:[UIColor blueColor] fromIndex:7 length:2];
[self.view addSubview:attrLabel];
并在viewDidAppear:
我想将文本更改为另一个字符串
// if the text going to change contains some chinese characters it will not work.
[attrLabel setText:@"222.00 元"];
[attrLabel setFont:[UIFont boldSystemFontOfSize:17] fromIndex:0 length:attrLabel.text.length];
[attrLabel setColor:[UIColor blueColor] fromIndex:0 length:10];
[attrLabel setColor:[UIColor redColor] fromIndex:0 length:6];
attributed label
上的文字在@" 222.00元"
请下载整个项目here https://github.com/bohanyzu/AttributedLabelTest.git
感谢。
答案 0 :(得分:0)
在drawRect方法中,请更改以下行:
for (int i = 0; i < [self.layer.sublayers count]; i++) {
CALayer *curLayer = [self.layer.sublayers objectAtIndex:i];
curLayer.hidden = YES;
[curLayer removeFromSuperlayer];
}
以下内容:
for (CALayer *subLayer in self.layer.sublayers) {
if ([subLayer isKindOfClass:[CATextLayer class]]) {
[subLayer removeFromSuperlayer];
}
}
原因是原始代码删除了UILabel的所有子层,其中包含UILabelContentLayer,更新文本时不会再次调用drawRect,因为UILabel只有一个CATextLayer。
/* The text layer provides simple text layout and rendering of plain
* or attributed strings. The first line is aligned to the top of the
* layer. */
如文档中所述,CATextLayer提供简单的文本布局,中文字符很复杂,所以让UILabel的默认图层完成工作。
当您将其设置为英文文本时,drawRect方法将被调用两次。但是如果中有中文字符,则只调用一次drawRect,这就是新文本未显示的原因。更改代码后,drawRect将被调用两次,从而更新文本。