Erent
Erent

Reputation: 621

Move view up when keyboard shows, for textfield in a stackview

I have a scenario were i move the view up when the keyboard appears, this scenario works fine however as soon as i start typing the view goes back to its original position. Something to note is that the textfield is in a stackview.

My question is that is there a way i can stop the view from going back to its original position when textEditing begins.

This is my code :

override func viewDidLoad() {

    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector:#selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector:#selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

 var isScroll = false


@objc func keyboardWillShow(sender: NSNotification) {
    mainView.frame.origin.y = -100
}
@objc func keyboardWillHide(sender: NSNotification) {
    mainView.frame.origin.y = 0
}

Upvotes: 1

Views: 1073

Answers (2)

Midhun Narayan
Midhun Narayan

Reputation: 879

add a scrollview as your base view and inside this add your contentview then

func keyboardShown(_ notification: Notification){

    var userInfo        = notification.userInfo!
    let keyboardSize    = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
    let contentInsets   = UIEdgeInsetsMake(0.0, 0.0, (keyboardSize!.height + 40), 0.0)
    self.mainScrollView.contentInset            = contentInsets
    self.mainScrollView.scrollIndicatorInsets   = contentInsets



    // **-- Scroll when keyboard shows up
    let aRect           = self.view.frame
    self.mainScrollView.contentSize = aRect.size

    /* if((self.activeTextField) != nil)
     {
     self.scrollView.scrollRectToVisible(self.activeTextField!.frame, animated: true)
     }*/

}

func keyboardHidden(_ notification: Notification) {

    let contentInsets   = UIEdgeInsets.zero
    self.mainScrollView.contentInset            = contentInsets
    self.mainScrollView.scrollIndicatorInsets   = contentInsets

    // **-- Scroll when keyboard shows up
    self.mainScrollView.contentSize = self.containerView.frame.size
}

Upvotes: 3

Rushabh Shah
Rushabh Shah

Reputation: 398

My personal opinion to use this library else you can manage the whole UI into the UITableview so no need to manage keyboardWillShow and keyboardWillHide method in that controller.

Upvotes: 1

Related Questions