swift2:设置textview委托是行不通的

时间:2015-11-27 06:40:42

标签: ios swift2

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不起作用

1 个答案:

答案 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
    }
    .....
}

另外,考虑将变量命名为实际意味着什么。如果代码伤害阅读,人们将不愿意帮助你。