Thursday, February 21, 2019

Textfield cover keyboard


When design user interface, if your TextField too low, keyboard show can cover TextField.
To make TextField auto scroll up, we put it in a ScrollView name Sc, add these functions in to above last close bracket.
func keyboardShow(n:NSNotification) {
        let d = n.userInfo!
        var r = (d[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        r = self.sc.convertRect(r, fromView:nil)
        self.sc.contentInset.bottom = r.size.height+50
        self.sc.scrollIndicatorInsets.bottom = r.size.height
    }
   
    func keyboardHide(sender: NSNotification!)
    {
        sc.setContentOffset(CGPointMake(0, 0), animated: false)
    }

Add these lines to below super.viewDidLoad().
NSNotificationCenter.defaultCenter().addObserver(
            self, selector: #selector(keyboardShow),
            name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(
            self, selector: #selector(ViewController.keyboardHide(_:)),
            name: UIKeyboardWillHideNotification, object: nil)


Now when you touch finger to TextField, it auto scroll up.

No comments:

Post a Comment