键盘上按“Enter”键时如何触发功能

问题描述 投票:0回答:2

当用户按下手机键盘上的“Enter”时,如何触发测试功能的按键回调功能?

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")
    }
}
ios swift delegates
2个回答
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
投票

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

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


@objc func editingDidEnd() {
    // Do whatever you would like here, in your case
    self.btnCallback()
}
© www.soinside.com 2019 - 2024. All rights reserved.