1

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.

user3573256
  • 219
  • 1
  • 2
  • 12

1 Answers1

2

Change your code to:

protocol NumericViewDelegate:NSObjectProtocol {
  func one()
}

class NumericView: UIView {

  var delegate: NumericViewDelegate?

  override init(frame: CGRect) {
    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)
    super.init(frame: frame)
    self.addSubview(oneButton)
  }

  required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
  }
}

In this way, it will compile well, however, your delegate is nil in init - it means nothing.

Forge
  • 6,538
  • 6
  • 44
  • 64
Leo
  • 24,596
  • 11
  • 71
  • 92