繁体   English   中英

将 function 参数传递给 Swift 中的选择器

[英]Pass function argument into selector in Swift

我一共有五个采摘者。 我想为每个人创建一个完成按钮。 我想为每个选择器使用不同的选择器来执行不同的操作。 为了设置完成按钮,我尝试对所有按钮使用相同的方法,但我不知道如何将 function 参数传递给 Swift 中的选择器。

func createDoneButton(txtField: UITextField, donePressed: /* What do I need here? */) {
    let toolbar = UIToolbar() // create toolbar
    toolbar.sizeToFit() // toolbar fits the size of the screen
        
    let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed)) // action when the done button was pressed
    toolbar.setItems([doneBtn], animated: true)
    txtField.inputAccessoryView = toolbar
}

你可以在你的问题中找到答案:) 只需使用Selector参数类型,不需要#selector()

    func createDoneButton(txtField: UITextField, donePressed: Selector){
        let toolbar = UIToolbar() // create toolbar
        toolbar.sizeToFit() // toolbar fits the size of the screen

        let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: donePressed) // action when the done button was pressed
        toolbar.setItems([doneBtn], animated: true)
        txtField.inputAccessoryView = toolbar
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM