zxc*_*cat 9 nslayoutmanager uitextview ios ios7
问题:在某些情况下UITextView默默地改变它contentSize.
最简单的案例textView与大文本和键盘.只需添加UITextView插座并设置- viewDidLoad为:
- (void)viewDidLoad {
[super viewDidLoad];
// expand default "Lorem..."
_textView.text = [NSString stringWithFormat:@"1%@\n\n2%@\n\n3%@\n\n4%@\n\n5", _textView.text, _textView.text, _textView.text, _textView.text];
_textView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
_textView.contentInset = UIEdgeInsetsMake(0, 0, 216, 0);
}
Run Code Online (Sandbox Code Playgroud)
现在显示和隐藏键盘会在某些情况下导致文本跳转.
我已经找到了按子类跳转的原因UITextView.我的子类中唯一的方法是:
- (void)setContentSize:(CGSize)contentSize {
NSLog(@"CS: %@", NSStringFromCGSize(contentSize));
[super setContentSize:contentSize];
}
Run Code Online (Sandbox Code Playgroud)
它显示contentSize了键盘隐藏的缩小和扩展.像这样的东西:
013-09-16 14:40:27.305 textView-bug2[11087:a0b] CS: {320, 651}
2013-09-16 14:40:27.313 textView-bug2[11087:a0b] CS: {320, 885}
2013-09-16 14:40:27.318 textView-bug2[11087:a0b] CS: {320, 902}
Run Code Online (Sandbox Code Playgroud)
看起来UITextViewiOS7中的行为发生了很大变化.有些事情现在已经破裂了.
进一步发现我发现layoutManagertextView的新属性也发生了变化.现在日志中有一些有趣的信息:
2013-09-16 14:41:59.352 textView-bug2[11115:a0b] CS: {320, 668}
<NSLayoutManager: 0x899e800>
1 containers, text backing has 2129 characters
Currently holding 2129 glyphs.
Glyph tree contents: 2129 characters, 2129 glyphs, 3 nodes, 96 node bytes, 5440 storage bytes, 5536 total bytes, 2.60 bytes per character, 2.60 bytes per glyph
Layout tree contents: 2129 characters, 2129 glyphs, 532 laid glyphs, 13 laid line fragments, 4 nodes, 128 node bytes, 1048 storage bytes, 1176 total bytes, 0.55 bytes per character, 0.55 bytes per glyph, 40.92 laid glyphs per laid line fragment, 90.46 bytes per laid line fragment
Run Code Online (Sandbox Code Playgroud)
并与contentSize下一行= {320, 885}包含Layout tree contents: ..., 2127 laid glyphs, 51 laid line fragments.所以看起来某种autolayout尝试在键盘上重新布局textView并更改contentSize,即使布局还没有完成.即使我的textView在键盘显示/隐藏之间没有变化,它也会运行.
问题是:如何防止contentSize更改?
看起来问题是在默认的layoutManager中UITextView.我已经决定对它进行子类化,并查看重新布局的启动位置和原因.但是NSLayoutManager使用默认设置进行简单创建可以解决问题.
这是我的演示项目中的代码(不完美)(参见问题).该_textView有一个出口,所以我从上海华盈将其删除.此代码放在- 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];
Run Code Online (Sandbox Code Playgroud)
MyTextView这是一个子类UITextView,详见问题.
有关详情,请参阅:
| 归档时间: |
|
| 查看次数: |
6927 次 |
| 最近记录: |