【发布时间】:2015-03-06 00:44:18
【问题描述】:
我在 iOS 开发中看到 UILabel 及其子视图的奇怪行为。 我想在 UILabel 上有一个覆盖视图,并且只想更改标签的文本。
当文本是数字或字母时效果很好。 但是,当我将文本更改为 Unicode 字符串时,子视图消失了。
为了重现这个问题,我创建了一个简单的项目,它只有一个标签和一个按钮。
标签有一个“A”作为初始文本。 当点击按钮时,会调用下面的方法,循环改变UILabel的文本。
- (void)pushButton:(id)sender
{
if ([[_label text] isEqualToString:@"A"]) {
[_label setText:@"B"];
// add a subview on the label
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
[view setBackgroundColor:[UIColor blueColor]];
[_label addSubview:view];
} else if ([[_label text] isEqualToString:@"B"]) {
[_label setText:@"C"];
} else if ([[_label text] isEqualToString:@"C"]) {
[_label setText:@"D"];
} else if ([[_label text] isEqualToString:@"D"]) {
[_label setText:@"\u2605"];
// after this, the subview disappears
} else {
[_label setText:@"A"];
// after this, the subview appears again
}
}
当我第一次点击按钮时,文本变为“B”并出现子视图。
第二次和第三次,文字改成“C”和“D”,子视图还在。
然而第四次,文字变成了“★”,子视图消失了。
第五次,文字变为“A”,再次出现子视图。
在这段代码中,我没有删除子视图,并且在每个循环中都会创建新的子视图。 但是,在任何时候将文本更改为“★”,所有这些子视图都会消失。
如何让子视图显示在 UILabel 上?
【问题讨论】:
标签: ios uilabel subview unicode-string