覆盖文本属性的UITextfield Bad Access

时间:2016-06-06 12:09:32

标签: ios iphone swift uitextfield textfield

这就是我在UITextfield的子类中所做的,

override public var text:String?  {
didSet {            
     NSLog("text = \(text)")
}
willSet {
    NSLog("will change from \(text) to \(newValue)")
}}

现在,当我使用myTextField.text将值设置为变量时,它显示Bad Access。当我记录文本时,它显示一些垃圾值作为文本。

1 个答案:

答案 0 :(得分:1)

查看UITextField的这个子类。

//  CustomTextField.swift

import UIKit

class CustomTextField: UITextField {
    override internal var text : String? {
        didSet {
            if !(text != nil && text!.isEmpty) {
                print("text = \(text)")
            }

        }

    willSet {
        if !(text != nil && text!.isEmpty) {
            print("will change from \(text) to \(newValue)")
        }
    }

}
}

我查看了View Controller。它有效:

override func viewDidLoad() {
        super.viewDidLoad()
        sampleTextField.text = "sample Text -1"
    }
    override func viewDidAppear(animated: Bool) {
        sampleTextField.text = "sample Text - 2"
    }