【发布时间】:2011-09-08 10:39:26
【问题描述】:
在 iPhone 的上下文中:
我有一个UIScrollView,其中包含一个UIImage。当用户点击UIImage 内的屏幕时,会在用户触摸的位置添加UITextField。用户可以编辑这个UITextField,文本框会根据添加或删除文本自动调整大小。
当正在编辑的UITextField 增加其宽度时,滚动视图会自动滚动以显示增加的宽度。
问题出现是因为文本字段的自动滚动不尊重屏幕的 y 值
例如,假设用户在图像底部添加了一个文本字段。当他们去编辑该文本字段时,键盘将显示,隐藏文本字段。我有代码可以滚动屏幕以显示文本字段。当用户输入太多文本以至于文本字段超出屏幕边缘时,问题就出现了。发生这种情况时,屏幕会水平滚动以适应更宽的文本,但也会垂直滚动 - 垂直滚动最终会隐藏文本字段,基本上会使我为显示文本字段所做的一切无效。
如果文本字段被键盘隐藏,则显示该文本字段的代码:
- (void)keyboardWasShown:(NSNotification*)notification
{
NSDictionary* info = [notification userInfo];
CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
self.offset = self.contentOffset;
CGRect frame = self.frame;
// self.activeField is the name of the field that is the current first responder - this just adds a little bit of padding
frame.size.height -= keyboardSize.height + (self.activeField.frame.size.height * 2);
if (!CGRectContainsPoint(frame, self.activeField.frame.origin)) {
CGPoint scrollPoint = CGPointMake(self.offset.x, self.activeField.frame.origin.y - keyboardSize.height + (activeField.frame.size.height * 2));
[self setContentOffset:scrollPoint animated:YES];
}
}
这是增加文本字段大小的代码:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
CGSize stringSize = [string sizeWithFont:textField.font];
CGSize newSize = [newString sizeWithFont:textField.font];
// Make textField wider if we're close to running up against it
if (newSize.width > (textField.frame.size.width - self.widthOffset)) {
CGRect textFieldFrame = textField.frame;
if (stringSize.width > self.widthOffset) {
textFieldFrame.size.width += stringSize.width;
}
textFieldFrame.size.width += self.widthOffset;
textField.frame = textFieldFrame;
}
// Shrink the textField if there is too much wasted space
if ((textField.frame.size.width - newSize.width) > self.widthOffset) {
CGRect textFieldFrame = textField.frame;
textFieldFrame.size.width = newSize.width + self.widthOffset;
textField.frame = textFieldFrame;
}
return YES;
}
问题是:如何让UIScrollView在自动滚动时尊重自身的y值?
【问题讨论】:
-
如果你能提供一个示例项目的链接会有所帮助。
标签: iphone objective-c cocoa-touch uikit uiscrollview