2
[self.scrollView scrollRectToVisible:textField.bounds animated:YES];

我似乎根本无法让我的 UIScrollView 滚动,以免它掩盖我的 UITextField。我认为 scrollRectToVisible 将是我的救星,但看起来不行。也许我错过了将我的 textField 坐标转换为我的滚动视图之类的东西。无论哪种方式,请查看我的示例项目。

https://github.com/stevemoser/Programming-iOS-Book-Examples/tree/master/ch20p573scrollViewAutoLayout2

哦,这个项目可能缺少委托连接,但我检查了它仍然没有滚动。

我见过与此类似的其他问题,但没有提到 Autolayout。

4

2 回答 2

8

scrollRectToVisible::转换为自动布局后,我也遇到了问题。我只是将其更改为直接调用,setContentOffset::然后它又开始工作了。

于 2013-03-09T08:13:26.810 回答
0

我遇到了同样的问题,我想将自动布局的 UITextEdit 滚动到视图中,而不使其成为第一响应者。

对我来说,问题是 UITextField 的边界是稍后在自动布局传递期间设置的,因此如果您在设置布局后立即执行此操作,则边界还无效。

要解决方法,我确实创建了 UITextField 的后代,并覆盖setBounds:并添加了一个 0 计时器以“稍后”滚动到视图中(你不能在那一刻滚动,因为系统的自动布局通道可能还没有完成)

@interface MyTextField: UITextField
{
  bool _scrollIntoView;
}
..
@end
@implementation MyTextField
-(void)setBounds:(CGRect)bounds
{
  bool empty=CGRectIsEmpty(self.bounds);
  bool isFirstResponder=self.isFirstResponder;
  [super setBounds:bounds];
  if (empty && !isFirstResponder && _scrollIntoView) 
    [self performSelector:@selector(scrollIntoViewLater) withObject:nil afterDelay:0];
  else if (empty && isFirstResponder)
    [self performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0];
}

-(void)scrollIntoViewLater
{
  CGRect r=[scrollView convertRect:self.bounds fromView:self];
  [scrollView scrollRectToVisible:r animated:TRUE];
}
@end

如果该字段应该可以使用屏幕键盘进行额外编辑,只需稍后调用 becomeFirstResponder:它会使用私有scrollTextFieldToVisibleAPI自动滚动到键盘上方的视图中,然后调用滚动视图scrollRectToVisible:animated:

顺便说一句,您的示例链接已损坏...

于 2017-10-28T13:18:18.870 回答