class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let a = UITextView(frame: CGRect(x: 50, y: 50, width: 200, height: 50))
view.addSubview(a)
a.backgroundColor = UIColor.redColor()
let b = c()
a.delegate = b
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
class c:NSObject, UITextViewDelegate {
func textViewDidChange(textView: UITextView) {
print("A")
}
}
textViewDidChange不起作用
答案 0 :(得分:1)
委托是一个弱引用。如果在viewDidLoad
的本地范围内创建委托对象,它将被取消分配。您需要将委托对象保存到实例变量,以将引用和对象保留在内存中:
class ViewController: UIViewController {
var b: C!
override func viewDidLoad() {
super.viewDidLoad()
let a = UITextView(frame: CGRect(x: 50, y: 50, width: 200, height: 50))
view.addSubview(a)
a.backgroundColor = UIColor.redColor()
self.b = c()
a.delegate = b
}
.....
}
另外,考虑将变量命名为实际意味着什么。如果代码伤害阅读,人们将不愿意帮助你。