我一直在到处找这个,但我似乎找不到。我知道如何解雇使用Objective-C键盘,但我不知道如何使用Swift?有人知道吗?
当前回答
//Simple exercise to demonstrate, assuming the view controller has a //Textfield, Button and a Label. And that the label should display the //userinputs when button clicked. And if you want the keyboard to disappear //when clicken anywhere on the screen + upon clicking Return key in the //keyboard. Dont forget to add "UITextFieldDelegate" and
//"self.userInput.delegate = self" as below
import UIKit
class ViewController: UIViewController,UITextFieldDelegate {
@IBOutlet weak var userInput: UITextField!
@IBAction func transferBtn(sender: AnyObject) {
display.text = userInput.text
}
@IBOutlet weak var display: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//This is important for the textFieldShouldReturn function, conforming to textfieldDelegate and setting it to self
self.userInput.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//This is for the keyboard to GO AWAYY !! when user clicks anywhere on the view
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
//This is for the keyboard to GO AWAYY !! when user clicks "Return" key on the keyboard
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
其他回答
我得到了你
override func viewDidLoad() {
super.viewDidLoad() /*This ensures that our view loaded*/
self.textField.delegate = self /*we select our text field that we want*/
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("dismissKeyboard")))
}
func dismissKeyboard(){ /*this is a void function*/
textField.resignFirstResponder() /*This will dismiss our keyboard on tap*/
}
以下是如何通过点击其他地方来消除键盘,使用Swift 5只需两行。
(我讨厌添加另一个答案,但由于这是谷歌上的顶级结果,我将帮助像我这样的新手。)
在你的ViewController.swift中,找到viewDidLoad()函数。
加上这两行:
let tap: UIGestureRecognizer = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing))
view.addGestureRecognizer(tap)
如果你使用滚动视图,它会简单得多。
只需在故事板中交互式地选择解散。
你可以使用swift
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
view.endEditing(true)
}
一个简单的方法是选择文本字段并使用方法enditing (true)
e.g
exampleTextField.endEditing(true)
推荐文章
- 如何在iPhone/iOS上删除电话号码的蓝色样式?
- 检测视网膜显示
- 如何在UIImageView中动画图像的变化?
- 如何从iPhone访问SOAP服务
- 如何分配一个行动UIImageView对象在Swift
- 使用NSURLSession发送POST请求
- 如果用户强制退出,iOS会将我的应用启动到后台吗?
- 如何从iOS应用程序启动Safari和打开URL
- 在React Native中获取一个视图的大小
- 在iOS8中使用Swift更改特定视图控制器的状态栏颜色
- 打印一个可变内存地址在swift
- 应用程序加载器在上传iOS应用程序时卡住了“与iTunes商店进行身份验证”
- 自动布局- UIButton的固有大小不包括标题插入
- 如何更改导航栏上“后退”按钮的标题
- 我如何获得iOS 7默认的蓝色编程?