从UIBarButtonItem触发textFieldShouldReturn

时间:2017-11-02 03:02:30

标签: ios swift uitextfield uibarbuttonitem uitextfielddelegate

我正在尝试添加触发UIBarButtonItem的{​​{1}},但我收到此错误:

  

'#selector'的参数不是指'@objc'方法,属性或初始值设定项

的UIBarButtonItem

textFieldShouldReturn

textFieldShouldReturn:

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
}

该错误表明我应该向@objc func textFieldShouldReturn(_ textField: UITextField) { print("hi there!") } 添加objc,但我已经拥有了textFieldShouldReturn。我也尝试了以下内容:

是否有人了解我如何设置UIBarButtonItem来触发我的textFieldShouldReturn

2 个答案:

答案 0 :(得分:3)

这里有几个问题。

  1. textFieldShouldReturn方法是UITextFieldDelegate的委托方法。它只应由UITextField调用。它有一个参数 - 文本字段。
  2. UIBarButtonItem目标/选择器需要是特定于处理按下按钮的方法。选择器需要具有两个可能的签名之一。这可以是没有参数的方法,也可以是带有一个参数的方法,该参数将是触发事件的UIBarButtonItem
  3. 您正在尝试将不匹配的UITextFieldDelegate方法称为UIBarButtonItem的选择器。这简直不会奏效。
  4. 如果您希望文本字段委托和按钮选择器都执行相同的操作,那么让两个相应的方法中的每一个调用第三种常用方法。

    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方法获取对文本字段的引用。它不能作为参数传递给该方法,因此您需要具有引用文本字段的属性。

答案 1 :(得分:0)

使用此方法,您可以从按钮Action:

中调用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)
    }

您需要使用方法作为选择器而不仅仅是直接调用textfield的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()
    }

这是Delegate方法,名为

 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