How do I show the keyboard with a view above it?

前端 未结 2 1294
自闭症患者
自闭症患者 2021-01-16 15:15

When a user taps on a button, I\'d like the keyboard to pop up (which is easy), but I want a view that goes up along with it (sticking to the top of the keyboard). This vie

2条回答
  •  既然无缘
    2021-01-16 15:33

    go to your storyboard and add a view(lets call it topKeyboardView) at the bottom of your viewController. and give it the following constraints:

    bottom space to bottom layout = 0

    and then add the textfield*(i prefer using textView to make it change its height when the message gets too long...)* and your button(send) on top of topKeyboardView.

    lets code now.. go to your viewController.swift and add an IBOutlet to your textField and button and add this function:

        //this is will tell if the keyboard hidden or not
        func addKeyboardNotifications() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil)
    }
    
        // MARK:- Notification
        func keyboardWillShow(notification: NSNotification) {
            print("keyboard is up")
        }
    
        func keyboardWillHide(notification: NSNotification) {
            print("keyboard is down")
        }
    

    in your viewDidLoad call the function:

        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
            addKeyboardNotifications()
       }
    

    run it...

提交回复
热议问题