I am trying to display some attributed text in a UITextView by using NSTextContainer and NSTextStorage but I don't see anything drawn in the textview (textview itself is drawn with white background as desired but no attributed text in it)
I however, can do it by just setting the .attributedText property of UITextView to my attributed text string but I want to know what I am doing wrong here or what concepts I misunderstood. Hopefully someone can explain.
- (void) test
{
UIView *mainView = [[UIView alloc] initWithFrame:self.window.frame];
mainView.translatesAutoresizingMaskIntoConstraints = NO;
UITextView* textView = [[UITextView alloc] init];
textView.translatesAutoresizingMaskIntoConstraints = NO;
textView.backgroundColor = [UIColor whiteColor];
[mainView addSubview:textView];
[mainView removeConstraints:mainView.constraints];
// layout constraints
NSArray *constraintHorizontal = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[textView]-|" options:0 metrics:nil views:@{@"textView":mainView.subviews[0]}];
NSArray *constraintVertical = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[textView(>=100)]" options:0 metrics:nil views:@{@"textView":mainView.subviews[0]}];
[mainView addConstraints:constraintHorizontal];
[mainView addConstraints:constraintVertical];
NSString *data = @"This is some text where few words are colored and funky. Some more garbage text. ";
NSDictionary *attr = @{NSForegroundColorAttributeName:[UIColor redColor]};
NSMutableAttributedString *textToShow = [[NSMutableAttributedString alloc] initWithString:data attributes:attr];
NSRange r = {.location = 8, .length = 9};
[textToShow addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:r];
NSRange r2 = {.location = 23, .length = 4};
[textToShow addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:r2];
NSTextStorage* textStorage = [[NSTextStorage alloc] initWithAttributedString:textToShow];
CGSize cgs = textView.bounds.size;
NSTextContainer *textcont = [[NSTextContainer alloc] initWithSize:cgs];
// if i comment out these three lines and uncomment the
// following line (textView.attributedText .. ), then it works,
NSLayoutManager *layoutManager = textView.layoutManager;
[layoutManager addTextContainer:textcont];
[textStorage addLayoutManager:layoutManager];
//textView.attributedText = textToShow;
textView.scrollEnabled = NO;
UIViewController *vc = [[UIViewController alloc] init];
vc.view = mainView;
[vc.view layoutIfNeeded];
self.window.rootViewController = vc;
}
Update There was no problem with the code above. I forgot to add the following lines to application:didFinishLaunchingWithOptions.. method (after looking at the code of the user with accepted answer below)
//self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window makeKeyAndVisible];