keyboard done key action swift iOS doesn't wor

2019-03-10 21:00发布

I'm new in stackoverflow, I have a problem with new swift code. I have custom the return button on keyboard with "Done", but when I tap on it, don't befall anything... How can I hide the keyboard on tap it? I have added a code (found on this site) for hide the keyboard when you tap somewhere ,not in the keyboard, but I can't custom it with tap on "done" button... Thank you before!!

3条回答
一夜七次
2楼-- · 2019-03-10 21:25

The protocol methods have new signatures (Swift 4.1). IE:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

As the protocol methods are optional, using a wrong signature will silently fail.

查看更多
小情绪 Triste *
3楼-- · 2019-03-10 21:28
textField.delegate = self

can be replaced by enter image description here

This will create the necessary connections between your View, its component and will make the textFieldShouldReturn method work as expected.

查看更多
放荡不羁爱自由
4楼-- · 2019-03-10 21:46

Yo need to implement delegate method which is called when you hit done button:

func textFieldShouldReturn(textField: UITextField!) -> Bool {  
    textField.resignFirstResponder()
    return true
}

You also need to conform to UITextFieldDelegate protocol:

class MyViewController: UIViewController,UITextFieldDelegate // I assume you override UIview controller class if not add UITextFieldDelegate to your class

The last thing is set up your class to be a text field delegate:

textField.delegate = self
查看更多
登录 后发表回答