【问题标题】:Display attributed text of UILabel in UIView在 UIView 中显示 UILabel 的属性文本
【发布时间】:2013-07-03 00:05:19
【问题描述】:

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

NSMutableAttributedString *myString;

UILabel *myLabel;

UIView *myView;

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

[myLabel setAttributedText: myString];

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

【问题讨论】:

  • 您是使用故事板设置视图还是以编程方式添加视图 [self addSubview:mylabel] ?
  • 我以编程方式添加它们。
  • 添加标签以查看标签中设置的属性文本是什么关系?

标签: ios objective-c uiview uilabel


【解决方案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

【讨论】:

    【解决方案2】:

    您需要在BEFORE将AttributeText应用于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()
    

    如果你将 view.addSubview(label) 移到 label.attributedText = text 之后,这个标签将显示所有文本的相同属性

    【讨论】:

      猜你喜欢
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多