我已经实现了一个自定义的UITableViewCell,其中包含一个UITextView,在用户输入时自动调整大小,类似于“通讯录”应用中的“备注”字段。它在我的iPhone上正常工作,但是在iPad上测试时,出现了一些非常奇怪的行为:当你到达一行的末尾时,键盘会隐藏一毫秒,然后立即再次显示。我本来会将其视为一个小小的程序错误,但它实际上会导致数据丢失,因为如果您正在输入,则会丢失一个或两个字符。这是我的代码:
代码
// returns the proper height/size for the UITextView based on the string it contains.
// If no string, it assumes a space so that it will always have one line.
- (CGSize)textViewSize:(UITextView*)textView {
float fudgeFactor = 16.0;
CGSize tallerSize = CGSizeMake(textView.frame.size.width-fudgeFactor, kMaxFieldHeight);
NSString *testString = @" ";
if ([textView.text length] > 0) {
testString = textView.text;
}
CGSize stringSize = [testString sizeWithFont:textView.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap];
return stringSize;
}
// based on the proper text view size, sets the UITextView's frame
- (void) setTextViewSize:(UITextView*)textView {
CGSize stringSize = [self textViewSize:textView];
if (stringSize.height != textView.frame.size.height) {
[textView setFrame:CGRectMake(textView.frame.origin.x,
textView.frame.origin.y,
textView.frame.size.width,
stringSize.height+10)]; // +10 to allow for the space above the text itself
}
}
// as per: https://dev59.com/GG865IYBdhLWcg3wkfcW
- (void)textViewDidChange:(UITextView *)textView {
[self setTextViewSize:textView]; // set proper text view size
UIView *contentView = textView.superview;
// (1) the padding above and below the UITextView should each be 6px, so UITextView's
// height + 12 should equal the height of the UITableViewCell
// (2) if they are not equal, then update the height of the UITableViewCell
if ((textView.frame.size.height + 12.0f) != contentView.frame.size.height) {
[myTableView beginUpdates];
[myTableView endUpdates];
[contentView setFrame:CGRectMake(0,
0,
contentView.frame.size.width,
(textView.frame.size.height+12.0f))];
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
int height;
UITextView *textView = myTextView;
[self setTextViewSize:textView];
height = textView.frame.size.height + 12;
if (height < 44) { // minimum height of 44
height = 44;
[textView setFrame:CGRectMake(textView.frame.origin.x,
textView.frame.origin.y,
textView.frame.size.width,
44-12)];
}
return (CGFloat)height;
}
这些问题
这里是发生了什么:
- 这段代码在我的 iPhone 上和 iPhone 模拟器上完全正常。当我输入文本时,UITextView 会平稳地增长,并伴随着 UITableViewCell 一起。
- 然而,在 iPad 模拟器上它变得混乱了。当你输入到一行的末尾时,键盘消失然后立即重新出现,因此如果用户继续输入,应用程序会错过一个或两个字符。
- 以下是我注意到的一些其他奇怪行为的附加说明,这可能有助于解释它的原因:
- 另外,我发现在函数
textViewDidChange:(UITextView *)textView
中删除代码行[myTableView beginUpdates]; [myTableView endUpdates];
可以使 UITextView 正常增长,也不会显示和隐藏键盘,但不幸的是,UITableViewCell 的高度不会增长到正确的大小。 - 更新:遵循这些说明,我现在能够停止文本的奇怪移动;但键盘仍然会隐藏和显示,这非常奇怪。
- 另外,我发现在函数
有没有人有什么想法可以让 iPad 上的键盘继续显示,而不是在一行的末尾隐藏和显示?
P.S.:我不想使用 ThreeTwenty。