我有自定义控件,其中包含textField。示例代码如下所示:
@IBDesignable
class MyTextField: UIView {
private var _text: String?
private var textField: UITextField?
@IBInspectable var text: String? {
get {
return _text
} set (newValue) {
guard let txt = newValue else { return }
self._text = txt
//updateView()
}
}
override func awakeFromNib() {
super.awakeFromNib()
updateView()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
updateView()
}
func updateView() {
textField = UITextField(frame: CGRect(x: 0, y: 0, width: 97, height: 30))
self.addSubview(textField!)
textField!.text = self._text
}}
当我在代码中为自定义控件创建插座时,我可以set
发送文字属性,但我不能get
它。我究竟做错了什么 ?我是新手,所以我不明白......
修改
创建商店@IBOutlet var myTextField: MyTextField!
和
standardTextField
添加按钮并创建操作插座
案例1:工作正常
@IBAction func click(_ sender:UIButton){ myTextField.text = standardTextField.text }
案例2:不起作用
@IBAction func click(_ sender:UIButton){ standardTextField.text = myTextField.text }
在案例2之后,在standardTextField中只有我从对象检查器设置的值。如果我更改myTextField.text的值,则standardTextField仍显示来自对象检查器的原始值
答案 0 :(得分:0)
我在Xcode中复制了你的设置。案例2确实有效 - 当单击按钮时,standardTextField会显示MyTextField的文本。
注意:在MyTextField中,我假设您要创建textField
一次,而不是每次文本更新时重新创建它。但是,案例2在没有这种变化的情况下正在运作。
import UIKit
class ViewController: UIViewController {
@IBOutlet var myTextField: MyTextField!
@IBOutlet var standardTextField: UITextField!
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
button.addTarget(self, action: #selector(click(_:)), for: .touchUpInside)
}
@IBAction func click(_ sender: UIButton) {
// myTextField.text = standardTextField.text // Case 1 works
standardTextField.text = myTextField.text // Case 2 works
}
}
MyTextField控件:
import UIKit
@IBDesignable
class MyTextField: UIView {
private var _text: String?
private var textField = UITextField(frame: CGRect(x: 0, y: 0, width: 97, height: 30))
@IBInspectable var text: String? {
get {
return _text
} set (newValue) {
guard let txt = newValue else { return }
self._text = txt
updateView()
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.addSubview(textField)
updateView()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self.addSubview(textField)
updateView()
}
func updateView() {
textField.text = self._text
}
}
答案 1 :(得分:0)
不工作getter的简单解决方案是更改文本属性 的从强>:
@IBInspectable var text: String? {
get {
return _text
} set (newValue) {
guard let txt = newValue else { return }
self._text = txt
updateView()
}
}
以强>
@IBInspectable var text: String? {
get {
return textField!.text
} set (newValue) {
guard let txt = newValue else { return }
self._text = txt
updateView()
}
}
但我不知道这是否正确...... 它有意义吗?