【问题标题】:Pass function argument into selector in Swift将函数参数传递给 Swift 中的选择器
【发布时间】:2020-07-17 13:55:20
【问题描述】:

我总共有五个选择器。我想为每个人创建一个完成按钮。我想为每个选择器使用不同的选择器来执行不同的操作。为了设置完成按钮,我尝试对所有按钮使用相同的方法,但我不知道如何将函数参数传递给 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
}

【问题讨论】:

标签: ios swift parameter-passing selector uitoolbar


【解决方案1】:

你可以在你的问题中找到答案:) 只需使用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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-01
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    相关资源
    最近更新 更多