replace layout manager of uitextview

时光毁灭记忆、已成空白 提交于 2020-02-15 08:23:12

问题


NSTextContainer on Mac OS X has a method replaceLayoutManager: to replace the NSLayoutManager of NSTextView with a subclass of NSLayoutManager.

Unfortunately iOS doesn't have such a function. I tried a combination of these lines of code, but it keeps crashing.

THLayoutManager *layoutManager = [[THLayoutManager alloc] init];
    [layoutManager addTextContainer:[self textContainer]];

    //      [[self textStorage] removeLayoutManager:[self layoutManager]];
    //[[self textStorage] addLayoutManager:layoutManager];
    [[self textContainer] setLayoutManager:layoutManager];

What is the correct procedure to replace the NSLayoutManager of an UITextview?


回答1:


Have a look at the WWDC2013 Intro To Text Kit video and sample code where they show how to do it.

https://developer.apple.com/downloads/index.action?name=WWDC%202013 https://developer.apple.com/wwdc/videos/

Below is an extract from the code

-(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] } };
}


来源:https://stackoverflow.com/questions/20909795/replace-layout-manager-of-uitextview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!