当文本更改为 Unicode 字符串时,UILabel 的子视图消失

Subview of UILabel disappears when the text was changed to Unicode string

我在 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 上?

UILabel 不打算有子视图。解决方案是让您的蓝色矩形成为您标签的父视图 的子视图。您可以将其放置在您的 UILabel 前面。

因此,您拥有此代码的地方:

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
[view setBackgroundColor:[UIColor blueColor]];
[_label addSubview:view];

你会这样说:

UIView *sup = [_label superview];
UIView *view = [UIView new];
[view setBackgroundColor:[UIColor blueColor]];
CGRect r = CGRectMake(0,0,20,20);
r = [sup convertRect:r fromView:_label];
view.frame = r;
[sup addSubview: view];