简体   繁体   中英

Why UIScrollView doesn't scroll when keyboard is shown?

I have an UITextField in my UIScrollView. This is the code to scroll the view when the keyboard is shown so that the UITextField stays visible :

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

hope this helps !

I found the solution following m.eldehairy answer.

// 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM