0

So I'm trying to get attributed text with various colors to display on a UIView. My variables are

NSMutableAttributedString *myString;

UILabel *myLabel;

UIView *myView;

First, I did the following in order to assign myLabel's attributedText to myString

[myLabel setAttributedText: myString];

Now I'm not entirely sure how to add myLabel to myView in order to make it so that the attributed text shows up. It seems that UIView's acknowledge UILabel textfields but not attributedtextfields

3
  • Are you using storyboards to setup the views or adding them programmatically [self addSubview:mylabel] ? Commented Jul 3, 2013 at 0:22
  • I'm adding them programmically. Commented Jul 3, 2013 at 0:58
  • What is the relationship in adding a label to view with attributed text setted in label? Commented Jul 3, 2013 at 5:03

2 Answers 2

1

I don't think it makes a difference for the view if you are adding a label with attributed string or regular string. You just addSubview:MyLabel
Check out the code bellow.

//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
Sign up to request clarification or add additional context in comments.

Comments

0

You need to addSubview BEFORE applying attributedText to 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()

if you move view.addSubview(label) after label.attributedText = text, this label will show same attributes for all text

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.