【问题标题】:Delegation in Swift - Error Cannot invoke addTarget with an argument listSwift 中的委派 - 错误无法使用参数列表调用 addTarget
【发布时间】:2015-05-27 09:22:10
【问题描述】:

我正在尝试在 Swift 中使用委托模式并得到以下代码:

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
}
*/

}

但是声明self.delegate!在addTarget 中不起作用。我收到错误:

无法使用类型参数列表调用“addTarget” '(NumericViewDelegate,动作:字符串,forControlEvents: UIControlEvents)。

addTarget 中声明self 时有效,但这不是预期的行为。

【问题讨论】:

标签: ios swift


【解决方案1】:

将您的代码更改为:

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)
  }
}

这样,它会编译得很好,但是,init 中的委托是 nil - 这意味着什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 2017-03-20
    相关资源
    最近更新 更多