所以我试图在UIView
上显示各种颜色的属性文本。我的变量是
NSMutableAttributedString *myString
;
UILabel *myLabel;
UIView *myView;
首先,为了将myLabel的attributedText分配给myString
,我执行了以下操作[myLabel setAttributedText: myString];
现在我不完全确定如何将myLabel
添加到myView
以便使其显示属性文本。似乎UIView's
承认UILabel textfields
但不承认attributedtextfields
答案 0 :(得分:1)
如果您要添加带有属性字符串或常规字符串的标签,我认为这对视图没有影响。你只需添加子视图: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
答案 1 :(得分:0)
您需要添加子视图 BEFORE 将attributionText应用于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),则此标签将显示所有文本的相同属性