Swift - 无法分配给 `newView` 中的 `delegate`
Swift - Cannot assign to `delegate` in `newView`
我正在使用 Swift 为我创建的自定义 class 实现委托。但是,当尝试将委托设置为自我时,我收到一条错误消息,指出“无法分配给 'newView' 中的 'delegate'。我在这里遗漏了什么吗?
在我的视图控制器中:
class ViewController: UIViewController, MyDelegate...
var newView = MyClass(frame: CGRectMake(pointX, pointY, 80, 80))
newView.delegate = self
func sayHi() {
print("Hi");
}
在我的习惯中 class:
protocol MyDelegate {
func sayHi()
}
class MyClass: UIView {
let delegate : MyDelegate?
func someMethod() {
delegate?.sayHi()
}
}
感谢您的帮助!
您使用 let
声明了 delegate
属性。因此,它只能在构造函数中赋值。将其更改为 var delegate
,它应该可以工作。
我正在使用 Swift 为我创建的自定义 class 实现委托。但是,当尝试将委托设置为自我时,我收到一条错误消息,指出“无法分配给 'newView' 中的 'delegate'。我在这里遗漏了什么吗?
在我的视图控制器中:
class ViewController: UIViewController, MyDelegate...
var newView = MyClass(frame: CGRectMake(pointX, pointY, 80, 80))
newView.delegate = self
func sayHi() {
print("Hi");
}
在我的习惯中 class:
protocol MyDelegate {
func sayHi()
}
class MyClass: UIView {
let delegate : MyDelegate?
func someMethod() {
delegate?.sayHi()
}
}
感谢您的帮助!
您使用 let
声明了 delegate
属性。因此,它只能在构造函数中赋值。将其更改为 var delegate
,它应该可以工作。