按"输入"如何触发功能在键盘上

时间:2018-03-01 19:18:32

标签: ios swift delegates

当用户按下"输入"时,如何触发测试功能的按钮回调功能?在手机的键盘上?

import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var textfield: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.textfield.delegate = self 
    }

    @IBAction func btn(_ sender: Any) {
        //textfield.resignFirstResponder()
        label.text = textfield.text!
        print("\n func completed \n")
    }

    func test(textField: UITextField!) {
        textfield.resignFirstResponder()
        print("\n func completed \n")
    }
}

2 个答案:

答案 0 :(得分:2)

你可以直接试试

func textFieldShouldReturn(_ textField: UITextField) -> Bool {    
   textField.resignFirstResponder() // options 1
   self.test(textField)  // option 2
   self.calledFromAnyWhere() // option 3  
   return true
}

修改:如果您想调用按钮的操作,则首选制作共享功能

 @IBAction func btn(_ sender: Any) {

   self.calledFromAnyWhere()
}

func calledFromAnyWhere()
{
    // any content
}

答案 1 :(得分:1)

您可以添加目标来处理特定事件,如下所示:

textField.addTarget(self, action: #selector(editingDidEnd), for: .editingDidEndOnExit)


@objc func editingDidEnd() {
    // Do whatever you would like here, in your case
    self.btnCallback()
}