2015-11-27 39 views
-1
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不行swift2:設置TextView的委託不行

+0

請澄清您的問題以及您需要哪些方面的幫助。它可以幫助您獲得更簡潔的答案 – shrmn

回答

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

另外,考慮命名變量實際上意味着什麼。如果代碼難以閱讀,人們不會願意幫助你。