uitextview的替换布局管理器

问题描述 投票:3回答:2

在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的正确过程是什么?

ios7 uitextview nslayoutmanager
2个回答
3
投票

[看一下WWDC2013文本简介视频和示例代码,他们演示如何做。

https://developer.apple.com/downloads/index.action?name=WWDC%202013https://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] } };
}

0
投票

自iOS9起,NSTextContainer具有与macOS相同的方法。因此,现在您可以用自己的子类替换情节提要UITextView上的布局管理器:

textView.textContainer.replaceLayoutManager(MyLayoutManager())
© www.soinside.com 2019 - 2024. All rights reserved.