Mac OS X上的NSTextContainer有一个方法replaceLayoutManager:用NSLayoutManager的子类替换NSTextView的NSLayoutManager。
不幸的是,iOS没有这样的功能。 我尝试了这些代码行的组合,但它一直在崩溃。
THLayoutManager *layoutManager = [[THLayoutManager alloc] init];
[layoutManager addTextContainer:[self textContainer]];
// [[self textStorage] removeLayoutManager:[self layoutManager]];
//[[self textStorage] addLayoutManager:layoutManager];
[[self textContainer] setLayoutManager:layoutManager];
更换UITextview的NSLayoutManager的正确程序是什么?
答案 0 :(得分:3)
查看WWDC2013 Intro To Text Kit视频和示例代码,了解如何操作。
https://developer.apple.com/downloads/index.action?name=WWDC%202013 https://developer.apple.com/wwdc/videos/
以下是代码摘录
-(void)viewDidLoad
{
[super viewDidLoad];
// our auto layout views use a design spec that calls for
// 8 pts on each side except the bottom
// since we scroll at the top here, only inset the sides
CGRect newTextViewRect = CGRectInset(self.view.bounds, 8., 0.);
self.textStorage = [[TKDInteractiveTextColoringTextStorage alloc] init];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
NSTextContainer *container = [[NSTextContainer alloc] initWithSize:CGSizeMake(newTextViewRect.size.width, CGFLOAT_MAX)];
container.widthTracksTextView = YES;
[layoutManager addTextContainer:container];
[_textStorage addLayoutManager:layoutManager];
UITextView *newTextView = [[UITextView alloc] initWithFrame:newTextViewRect textContainer:container];
newTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
newTextView.scrollEnabled = YES;
newTextView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
[self.view addSubview:newTextView];
self.textView = newTextView;
self.textStorage.tokens = @{ @"Alice" : @{ NSForegroundColorAttributeName : [UIColor redColor] },
@"Rabbit" : @{ NSForegroundColorAttributeName : [UIColor orangeColor] },
TKDDefaultTokenName : @{ NSForegroundColorAttributeName : [UIColor blackColor] } };
}
答案 1 :(得分:1)
自iOS9起,NSTextContainer具有与macOS相同的方法。因此,现在您可以用自己的子类替换情节提要UITextView上的布局管理器:
textView.textContainer.replaceLayoutManager(MyLayoutManager())