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
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.