[英]Why UIScrollView doesn't scroll when keyboard is shown?
I have an UITextField in my UIScrollView. 我的UIScrollView中有一个UITextField。 This is the code to scroll the view when the keyboard is shown so that the UITextField stays visible :
这是在显示键盘时滚动视图以使UITextField保持可见的代码:
func keyboardWasShown(aNotification:NSNotification) {
let info: NSDictionary = aNotification.userInfo!
let value: NSValue = info.valueForKey(UIKeyboardFrameBeginUserInfoKey) as NSValue
let keyboardSize: CGSize = value.CGRectValue().size
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0)
theScrollView.contentInset = contentInsets
theScrollView.scrollIndicatorInsets = contentInsets
var aRect: CGRect = self.view.frame
aRect.size.height -= keyboardSize.height
let activeTextFieldRect: CGRect? = nicknameLabel?.frame
let activeTextFieldOrigin: CGPoint? = activeTextFieldRect?.origin
if (!CGRectContainsPoint(aRect, activeTextFieldOrigin!)) {
theScrollView.scrollRectToVisible(activeTextFieldRect!, animated:true)
}
}
What am I doing wrong ? 我究竟做错了什么 ?
i had this problem when i had a scroll view in storyboard with AutoLayout , the problem is that UIScrollView with AutoLayout doesn't know its content size even if you set its content size programmatically , its content size is inferred from the constraints applied to its content views , and it can be quite messy if you have many subviews in the scroll view content , so i solved the problem by adding all subviews in the scrollview to a root view and add this root view as the content of my scroll view , and of course pin top , left , bottom , right , width and height of this root view to the scrollview , this way the scrollview knows its content view's size exactly , here is a technical note issued by apple about this problem https://developer.apple.com/library/ios/technotes/tn2154/_index.html 当我在带有AutoLayout的情节提要中使用滚动视图时,我遇到了这个问题,问题是即使您以编程方式设置了UILayoutView的AutoLayout,它的内容大小也不知道其内容大小,它的内容大小是根据对其内容施加的约束来推断的视图,如果滚动视图内容中有许多子视图,可能会很混乱,因此我通过将滚动视图中的所有子视图添加到根视图并将此根视图添加为滚动视图的内容来解决了该问题,并且当然,将此根视图的顶部,左侧,底部,右侧,宽度和高度固定在scrollview上,这样,scrollview就能准确地知道其内容视图的大小,这是苹果公司发布的有关此问题的技术说明https://developer.apple .com / library / ios / technotes / tn2154 / _index.html
hope this helps ! 希望这可以帮助 !
I found the solution following m.eldehairy answer. 我在m.eldehairy回答之后找到了解决方案。
// I add all my subviews in a contentView with a predefined HEIGHT and WIDTH
let contentView = UIView(frame: CGRect(x: 0, y: 0, width: WIDTH, height: HEIGHT))
contentView.addSubview(view1)
contentView.addSubview(view2)
...
// I embed my contentView in the scrollView, and set its content size
myScrollView.addSubview(contentView)
myScrollView.contentSize = CGSizeMake(WIDTH, HEIGHT)
It works. 有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.