I'm trying to use the delegation pattern in Swift and have got the following code:
protocol NumericViewDelegate {
func one()
}
class NumericView: UIView {
var delegate: NumericViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
var oneButton = UIButton(frame: CGRectMake(0.0, 100.0, 200.0, 100.0))
oneButton.titleLabel?.text = "one"
oneButton.backgroundColor = UIColor.blueColor()
oneButton.addTarget(self.delegate!, action: "one:", forControlEvents: UIControlEvents.TouchUpOutside)
self.addSubview(oneButton)
}
required init(coder aDecoder: NSCoder
) {
super.init(coder: aDecoder)
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
But declaring self.delegate
! in addTarget
doesn't work. I receive the error:
Cannot invoke 'addTarget' with an argument list of type '(NumericViewDelegate, action: String, forControlEvents: UIControlEvents).
It works when declaring self
in addTarget
, but that's not the intended behaviour.