How to hide keyboard when using SwiftUI?

2020-01-27 02:53发布

How to hide keyboard using SwiftUI for below cases?

Case 1

I have TextField and I need to hide the keyboard when the user clicks the return button.

Case 2

I have TextField and I need to hide the keyboard when the user taps outside.

How I can do this using SwiftUI?

Note:

I have not asked a question regarding UITextField. I want to do it by using SwifUI(TextField).

13条回答
兄弟一词,经得起流年.
2楼-- · 2020-01-27 03:42

I found another way to dismiss the keyboard that doesn't require accessing the keyWindow property; as a matter of fact the compiler gives back a warning using

UIApplication.shared.keyWindow?.endEditing(true)

'keyWindow' was deprecated in iOS 13.0: Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes

Instead I used this code:

UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to:nil, from:nil, for:nil)
查看更多
登录 后发表回答