gpt4 book ai didi

swift - 有没有办法在Swift中使用#selector调用带参数的函数

转载 作者:行者123 更新时间:2023-11-28 16:12:30 26 4
gpt4 key购买 nike

我有一个 UIToolbar 项数组,显示 inputField 何时成为第一响应者。

//... code
toolBar.items = [
UIBarButtonItem(title: "Button 1", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(myFunction))]

myInputField.inputAccessoryView = toolBar

是否可以使用参数调用上述示例中的myFunction

有点像...

... #selector(myFunction(someParameter)))

最佳答案

类似于UIButton,可以通过UIBarButtonItemtag属性传递参数。

override func viewDidLoad() {
super.viewDidLoad()

let toolBar = UIToolbar()
let firstButton = UIBarButtonItem(title: "Button 1", style: UIBarButtonItemStyle.Done, target: self, action: #selector(myFunction))
let secondButton = UIBarButtonItem(title: "Button 2", style: UIBarButtonItemStyle.Done, target: self, action: #selector(myFunction))
firstButton.tag = 1
secondButton.tag = 2
toolBar.items = [ firstButton, secondButton ]
toolBar.sizeToFit()
textField.inputAccessoryView = toolBar
}

func myFunction(sender: UIBarButtonItem) {
print("Tapped: \(sender.tag)")
}

在此示例中,点击按钮会打印按钮的标签:

Tapped: 1   // Tap button 1
Tapped: 2 // Tap button 2

关于swift - 有没有办法在Swift中使用#selector调用带参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39400877/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com