3

Mac OS X 上的 NSTextContainer 有一个方法 replaceLayoutManager:将 NSTextView 的 NSLayoutManager 替换为 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 的正确程序是什么?

4

2 回答 2

4

从 iOS9 开始,NSTextContainer 的方法与 macOS 相同。所以现在你可以用你自己的子类替换你的故事板 UITextView 上的布局管理器:

textView.textContainer.replaceLayoutManager(MyLayoutManager())
于 2020-04-13T02:25:01.077 回答
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] } };
}
于 2014-01-04T02:26:09.437 回答