简体   繁体   中英

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

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 view will be have a "send a message.." textfield. When the user pushes done, I want the keyboard to go away along with the view.

How do I make this view "stick" to the keyboard?

UITextFields have a property called inputAccessoryView

- Apple Documentation

- Relevant Stack Overflow Answer

This will pin whatever view you assign as that textfield's inputAccessoryView to the top of the keyboard.

Something important from the answer in that link to remember:

Note that the view you use should neither be in the view hierarchy elsewhere, nor should you add it to some superview, this is done for you.

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

底部空间到底部布局= 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...

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