0

所以我试图让具有各种颜色的属性文本显示在UIView. 我的变量是

NSMutableAttributedString *myString;

UILabel *myLabel;

UIView *myView;

首先,为了将 myLabel 的属性文本分配给 myString,我执行了以下操作

[myLabel setAttributedText: myString];

现在我不完全确定如何添加myLabelmyView使其显示属性文本。似乎UIView's承认UILabel textfields但不承认attributedtextfields

4

2 回答 2

1

如果您添加带有属性字符串或常规字符串的标签,我认为这不会对视图产生影响。您只需添加Subview:MyLabel
查看下面的代码。

//setup the testview
    UIView *testView = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 100, 100)];
    [testView setBackgroundColor:[UIColor blackColor]];
    [self.view addSubview:testView];

    //setup the label
    UILabel *txtLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    [txtLabel setBackgroundColor:[UIColor redColor]];
    NSDictionary *attrib = @{NSForegroundColorAttributeName : [UIColor blueColor]};
    NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:@"test" attributes:attrib];
    txtLabel.attributedText = attribString;
    [testView addSubview:txtLabel]; //add the label to the testview
于 2013-07-03T03:25:18.820 回答
0

您需要在将属性文本应用于 UILabel之前添加子视图

let text = NSMutableAttributedString()
text.append(NSAttributedString(string: "AAA", attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 20)]))
text.append(NSAttributedString(string: "bbb", attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 10)]))

let label = UILabel()

view.addSubview(label)

label.attributedText = text
label.sizeToFit()

如果您在 label.attributedText = text 之后移动 view.addSubview(label),则此标签将为所有文本显示相同的属性

于 2017-11-08T11:06:34.690 回答