I have made a customizd attributed label
, it works well with alphabet or numeric characters. however, when change the text to some one contains Chinese(or Japanese, Korean etc) characters it will doesn't work.
For example
I have init the attributed label
, and set the text with 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];
and in the viewDidAppear:
I want to change the text to another string
// 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];
the text on the attributed label
will not change until you remove the character 元 in @"222.00 元".
please down load the entire project here https://github.com/bohanyzu/AttributedLabelTest.git
thanks.
In the drawRect method, please change the following line:
for (int i = 0; i < [self.layer.sublayers count]; i++) {
CALayer *curLayer = [self.layer.sublayers objectAtIndex:i];
curLayer.hidden = YES;
[curLayer removeFromSuperlayer];
}
to the following:
for (CALayer *subLayer in self.layer.sublayers) {
if ([subLayer isKindOfClass:[CATextLayer class]]) {
[subLayer removeFromSuperlayer];
}
}
The reason is that the original code remove all sublayers of UILabel, which includes a UILabelContentLayer, drawRect will not be called again when you update the text, since then UILabel only has a 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. */
As mentioned in document, CATextLayer provides simple text layout, Chinese characters is complicated, so let UILabel's default layer do the job.
When you set it to english text, the drawRect method will be called twice. But drawRect is called only once if there is Chinese characters in it, that's the reason the new text is not showed. After changing the code, drawRect will be called twice, thus updating your text.