繁体   English   中英

在UIView中显示UILabel的属性文本

[英]Display attributed text of UILabel in UIView

因此,我试图获取具有各种颜色的属性文本以显示在UIView 我的变量是

NSMutableAttributedString *myString ;

UILabel *myLabel;

UIView *myView;

首先,为了将myLabel的attributedText分配给myString,我执行了以下操作

[myLabel setAttributedText: myString];

现在,我不完全确定如何将myLabel添加到myView中以使其显示属性文本。 似乎UIView's承认UILabel textfields但不是attributedtextfields

我认为如果您添加带有属性字符串或常规字符串的标签,则对视图没有影响。 您只需添加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

您需要将attributedText应用于UILabel 之前先添加Subview

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),则此标签将为所有文本显示相同的属性

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM