iOS7以上系统中,UITextView输入滚动错位的bug

在iOS7中,UITextView多了一个textContainer属性用来描述一些Layout。

在用

1
UITextView *textView = [[UITextView alloc] init];

这个方法时,并没用初始化textContainer,会导致输入中文时页面滚动出现bug。修复这个bug,用以下的方法初始化。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@implementation SomeTextView
-(id)init
{
if (IOS7) {
NSTextStorage* textStorage = [[NSTextStorage alloc] init];
NSLayoutManager* layoutManager = [NSLayoutManager new];
[textStorage addLayoutManager:layoutManager];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(someWidth, someHeight)];
textContainer.widthTracksTextView = YES;
textContainer.heightTracksTextView = YES;
[layoutManager addTextContainer:textContainer];
if (self = [super initWithFrame:CGRectZero textContainer:textContainer]) {
}
}
else {
if (self = [super init]) {
}
}
return self;
}
- (id)initWithFrame:(CGRect)frame
{
if (IOS7) {
NSTextStorage* textStorage = [[NSTextStorage alloc] init];
NSLayoutManager* layoutManager = [NSLayoutManager new];
[textStorage addLayoutManager:layoutManager];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(frame.size.width, kDeviceHeight)];
textContainer.widthTracksTextView = YES;
textContainer.heightTracksTextView = YES;
[layoutManager addTextContainer:textContainer];
if (self = [super initWithFrame:frame textContainer:textContainer]) {
}
}
else {
if (self = [super initWithFrame:frame]) {
}
}
return self;
}
@end