UITextView contentSize changes and NSLayoutManager in iOS7

后端 未结 3 1025
不思量自难忘°
不思量自难忘° 2021-02-06 04:20

The problem: UITextView silently changes it\'s contentSize in some situations.

The simplest case textView with large text and keyboard. Just ad

3条回答
  •  独厮守ぢ
    2021-02-06 04:40

    Looks like the problem is in default layoutManager of UITextView. I've decided to subclass it and see, where and why re-layout being initiated. But simple creation of NSLayoutManager with default settings solved the problem.

    Here is code (not perfect) from my demo project (see in question). The _textView there was an outlet, so I remove it from superview. This code is placed in - viewDidLoad:

    NSTextStorage* textStorage = [[NSTextStorage alloc] initWithString:_textView.text];
    NSLayoutManager* layoutManager = [NSLayoutManager new];
    [textStorage addLayoutManager:layoutManager];
    _textContainer = [[NSTextContainer alloc] initWithSize:self.view.bounds.size];
    [layoutManager addTextContainer:_textContainer];
    [_textView removeFromSuperview];    // remove original textView
    _textView = [[MyTextView alloc] initWithFrame:self.view.bounds 
                                    textContainer:_textContainer];
    [self.view addSubview:_textView];
    

    MyTextView here is a subclass of UITextView, see question for details.

    For more info see:

    • About Text Handling in iOS
    • Using Text Kit to Draw and Manage Text
    • NSLayoutManager Class Reference for iOS

提交回复
热议问题