我试图通过使用UITextView和NSTextContainer在NSTextStorage中显示一些属性化文本,但在文本视图中没有看到任何绘制的内容(文本视图本身是按照需要用白色背景绘制的,但其中没有属性化文本)
不过,我只需将UITextView的UITextView属性设置为属性化文本字符串就可以做到这一点,但我想知道我在这里做错了什么,或者我误解了哪些概念。希望有人能解释。
- (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;
}更新上面的代码没有问题。我忘了在应用程序中添加以下行:didFinishLaunchingWithOptions。方法(在查看了用户的代码后,可以接受下面的答案)。
//self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window makeKeyAndVisible]; 发布于 2014-02-09 22:03:34
您的代码对我来说很好(Xcode 5.0.2)。这里提供了示例项目:
https://dl.dropboxusercontent.com/u/1365846/Test.zip https://dl.dropboxusercontent.com/u/1365846/Screen%20Shot%202014-02-09%20at%2023.11.22.png
根据“任择议定书”,他漏掉了以下几行:
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window makeKeyAndVisible];见评论。
https://stackoverflow.com/questions/21665578
复制相似问题