xcode ScrollRectToVisible未按预期工作

dy2hfwbg  于 2022-12-24  发布在  其他
关注(0)|答案(3)|浏览(82)

我有一个视图,它的文本字段从屏幕的顶部到底部都有。很明显,底部的文本字段在键盘弹出时会被键盘覆盖,所以我着手解决这个问题。
我在viewDidLoad方法中注册了通知,然后在发送UIKeyboardDidShowNotification时,调用此方法:

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;

    [scrollView scrollRectToVisible:activeField.frame animated:YES];
}

问题是什么都没有滚动,更不用说滚动到可见了。我在这里错过了什么?
我的所有文本字段都在滚动视图中,等等。
先谢了。

o3imoua4

o3imoua41#

This是一个类似的帖子,其中scrollRectToVisible:无法正常工作,有一个解决方案,确保contentSize设置正确。希望有帮助!

q7solyqu

q7solyqu2#

给未来的自己发信息:您的contentSize宽度为0。
当contentSize的宽度为0时,scrollRectToVisible不起作用。
此外,由于使用了自动版式,contentSize宽度为0。
参见https://developer.apple.com/library/archive/technotes/tn2154/_index.html
此外,这是因为您没有显式设置内容视图的宽度,而是做了一些愚蠢的事情,如在滚动视图中居中内容视图,也许是UIScrollView不够聪明,无法弄清楚如何在这种情况下在自动布局上下文中设置contentSize

qni6mghb

qni6mghb3#

我有一个UIScrollView可以在两个维度上滚动,它只有一个子视图。滚动视图的contentSize与子视图的边界大小不匹配,所以scrollRectToVisible(在子视图的坐标空间中使用提供的CGRect)不能滚动到正确的位置。转换坐标空间使它按预期工作:

let targetPoint = CGPoint(x: 200, y: 200)
let scrollTarget = contentView.convert(targetPoint, to: scrollView)
let targetRect = CGRect(center: scrollTarget, size: .init(width: 150, height: 150))
scrollView.scrollRectToVisible(targetRect, animated: false)

相关问题