从 UIBarButtonItem 触发 textFieldShouldReturn

Trigger textFieldShouldReturn from UIBarButtonItem

我正在尝试添加触发我的 textFieldShouldReturnUIBarButtonItem,但出现此错误:

Argument of '#selector' does not refer to an '@objc' method, property, or initializer

UIBarButtonItem

func addToolBar(textField: UITextField) {
    let toolBar = UIToolbar()
    toolBar.barStyle = .default
    let doneButton = UIBarButtonItem(
            title: "Done",
            style: .done,
            target: self,
            action: #selector(textFieldShouldReturn(textField))) //** ERROR **
    toolBar.isUserInteractionEnabled = true
    toolBar.sizeToFit()
    textField.inputAccessoryView = toolBar
}

textFieldShouldReturn:

@objc func textFieldShouldReturn(_ textField: UITextField) {
  print("hi there!")
}

错误提示我需要将 objc 添加到我的 textFieldShouldReturn,但我已经有了。我也已经尝试过以下方法:

有谁知道我如何设置我的 UIBarButtonItem 来触发我的 textFieldShouldReturn

你这里有几个问题。

  1. textFieldShouldReturn方法是UITextFieldDelegate的委托方法。它只能由 UITextField 调用。它有一个参数 - 文本字段。
  2. UIBarButtonItem target/selector 需要是一种特定于处理按下按钮的方法。选择器需要具有两个可能的签名之一。这可以是一个没有参数的方法,也可以是一个有一个参数的方法,该参数将是触发事件的 UIBarButtonItem
  3. 您正在尝试调用不匹配的 UITextFieldDelegate 方法作为 UIBarButtonItem 的选择器。那根本行不通。

如果您希望文本字段委托和按钮选择器执行相同的操作,则让两个相应的方法中的每一个调用第三个通用方法。

func textFieldShouldReturn(_ textField: UITextField) {
    processReturn()
}

@objc func barButtonAction(_ button: UIBarButtonItem) {
    processReturn()
}

func processReturn() {
    // Do whatever is needed
}

并设置条形按钮项目:

let doneButton = UIBarButtonItem(
        title: "Done",
        style: .done,
        target: self,
        action: #selector(barButtonAction)

如果您的 processReturn 方法需要对文本字段的引用,请添加该参数。诀窍是从 barButtonAction 方法获取对文本字段的引用。它不能作为参数传递给该方法,因此您需要有一个引用文本字段的 属性。

在这里,您可以通过按钮操作调用 textFieldSholdReturn 方法:

var textField : UITextField!



 override func viewDidLoad() {
        super.viewDidLoad()

        //Fixed space
        let fixed = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: self, action: nil)
        fixed.width = 10

        //Text
        let text = UIBarButtonItem(title: "My Title", style: UIBarButtonItemStyle.plain, target: self, action: nil)
        text.setTitleTextAttributes([
            NSAttributedStringKey.font : UIFont.systemFont(ofSize: 23.0),
            NSAttributedStringKey.foregroundColor : UIColor.white], for: UIControlState.normal)

        //TextField
        textField = UITextField(frame: CGRect(x: 0, y: 0, width: 150, height: 30))
        textField.delegate = self
        textField.textColor = UIColor.blue
        let border = CALayer()
        let width : CGFloat = 2.0
        border.borderColor = UIColor.white.cgColor
        border.frame = CGRect(x: 0, y: textField.frame.size.height-width, width: textField.frame.size.width, height: textField.frame.size.height)
        border.borderWidth = width
        textField.layer.addSublayer(border)
        textField.layer.masksToBounds = true
        let textFieldButton = UIBarButtonItem(customView: textField)

        //Search Button
        let search = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.search, target: self, action: #selector(ViewController.callExplictly(sender:)))

        //Flexible Space
        let flexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)

        //Toolbar
        let toolbar = UIToolbar(frame: CGRect(x: 0, y: 20 , width: view.frame.width, height: 50))
        toolbar.sizeToFit()
        toolbar.barTintColor = UIColor.orange
        toolbar.isTranslucent = false
        toolbar.tintColor = UIColor.white
        toolbar.items = [fixed, text, fixed, textFieldButton, flexible, search]
        view.addSubview(toolbar)
    }

你需要使用一个方法作为选择器而不是直接调用文本域的Delgate方法

-- 将选择器添加到 UIBarButton :

 //Search Button
 let search = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.search, target: self, action: #selector(ViewController.callExplictly(sender:)))

这里需要调用委托方法的方法

@objc func callExplictly(sender: UIBarButtonItem){
        print("its called")
        if let textField = textField, let textFieldDelegate = textField.delegate {
            if textFieldDelegate.textFieldShouldReturn!(textField) {
                textField.endEditing(true)
            }
        }
 //here let textField --- Here I am just using. reference to TextField used  = textField --- this is textField declared and being used in Bar 
 //I am calling textField.endEditing(true) to dismiss opened Keyboard as Done button refer that My action required on TF is completed now I can Dismiss keyboard too.
 // As here textFieldDelegate.textFieldShouldReturn!  -- (!) this symbolises as textFieldShouldReturn is a delegate method of TextField and I am accessing that using a reference which is not of textField Type So I am using ! as optional so, it dont jump over the function and call it

    }

 func textFieldDidBeginEditing(_ textField: UITextField) {

        view.backgroundColor = UIColor.yellow

    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.backgroundColor = UIColor.cyan

        //Hide the keyboard
        textField.resignFirstResponder()
    }

这是调用的委托方法

 func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        view.backgroundColor = UIColor.white
        print("Called")

        //Hide the keyboard
        textField.resignFirstResponder()
        return true
    }

另请查看我的代码文件供您参考:

Link : https://drive.google.com/open?id=0Bz8kF1Gedr7fcTdEX29WX1JvYlU