问题
Consider the following code, which prints "working" when a button is pressed:
protocol MyClassDelegate: class {
func foo()
}
class MyClass {
weak var delegate: MyClassDelegate?
func foo() {
delegate?.foo()
}
let button: UIButton = {
button.addTarget(self, action: #selector(foo), for: .touchUpInside)
return button
}()
}
class MyViewController { ... }
extension MyViewController: MyClassDelegate {
func foo() {
print("working")
}
}
When I try adding a parameter to MyClassDelegate's foo method, "working" stops printing (meaning the button stops working?). I.e.:
protocol MyClassDelegate: class {
func foo(_ str: String)
}
class MyClass {
weak var delegate: MyClassDelegate?
func foo() {
delegate?.foo("working")
}
let button: UIButton = {
button.addTarget(self, action: #selector(foo), for: .touchUpInside)
return button
}()
}
class MyViewController { ... }
extension MyViewController: MyClassDelegate {
func foo(_ str: String) {
print(str)
}
}
How can I get the second version of the code with the parameter to work? Thanks.
回答1:
You are calling a wrong method on the delegate . Your MyClassDelegate doesn't have method named showDetails() . Call your delegate method this way:
func foo() {
delegate?.foo("working")
}
回答2:
The problem was that button needs to be a declared with lazy var rather than with let.
回答3:
Did you do that: cell.delegate = self in your ViewController?
来源:https://stackoverflow.com/questions/43928901/swift-adding-parameter-to-protocol-function