【发布时间】:2014-12-04 22:57:20
【问题描述】:
我想知道您如何允许通过按软件键盘上的返回键或点击 UIButton 来执行操作。
UI 按钮已设置为执行 IBAction。
我如何还允许用户按键盘上的返回键来执行相同的操作?
【问题讨论】:
我想知道您如何允许通过按软件键盘上的返回键或点击 UIButton 来执行操作。
UI 按钮已设置为执行 IBAction。
我如何还允许用户按键盘上的返回键来执行相同的操作?
【问题讨论】:
确保你的类扩展了 UITextFieldDelegate 协议
SomeViewControllerClass : UIViewController, UITextFieldDelegate
您可以执行如下操作:
override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
//textField code
textField.resignFirstResponder() //if desired
performAction()
return true
}
func performAction() {
//action events
}
【讨论】:
斯威夫特 4.2:
以编程方式创建的文本字段的其他方法不需要委托:
MyTextField.addTarget(self, action: #selector(MyTextFielAction)
, for: UIControl.Event.primaryActionTriggered)
然后执行如下操作:
func MyTextFielAction(textField: UITextField) {
//YOUR CODE can perform same action as your UIButton
}
【讨论】:
如果您的部署目标是 iOS 9.0 或更高版本,您可以将文本字段的“Primary Action Triggered”事件连接到操作,如下所示:
我无法让“触发的主要操作”按建议工作。我使用了“编辑结束”,现在可以使用 Screenshot of Editing Did End
【讨论】:
这是一个完整的例子,两者都有:
重复按下按钮时用于书写以及清除标签和文本的按钮操作会交替执行两种操作
在按键时返回键盘,它会触发动作并退出第一响应者
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField1: UITextField!
@IBOutlet weak var label1: UILabel!
var buttonHasBeenPressed = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
textField1.delegate = self
}
@IBAction func buttonGo(_ sender: Any) {
performAction()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
performAction()
return true
}
func performAction() {
buttonHasBeenPressed = !buttonHasBeenPressed
if buttonHasBeenPressed == true {
label1.text = textField1.text
} else {
textField1.text = ""
label1.text = ""
}
}
}
【讨论】: