我正在尝试使用xib创建一个customView,下面是代码
import UIKit
class CustomView: UIView {
@IBOutlet var CustomView: UIView!
private var _isSelecteda:Bool!
var isSelecteda: Bool {
get {
return _isSelecteda
}
set {
_isSelecteda = isSelecteda
if _isSelecteda {
CustomView.backgroundColor = UIColor.white
CustomView.layer.borderColor = UIColor.black.cgColor
}
else {
CustomView.backgroundColor = Colors.searchGameCellBackgroundColor
CustomView.layer.borderColor = Colors.priceLabelBorderColor?.cgColor
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)
addSubview(CustomView)
self._isSelecteda = false
CustomView.layer.cornerRadius = 3
CustomView.layer.borderWidth = 1
self.clipsToBounds = true
CustomView.frame = self.bounds
}
@IBAction func btnSelectedTapped(_ sender: Any) {
isSelecteda = !isSelecteda
}
}
每当我尝试访问isSelecteda时,都会调用_isSelecteda的私有声明并重置该值。我的目标是从ViewController设置isSelected的值并更改其背景颜色。
根据我的理解,事实并非如此。非常奇怪
注意:我将Xcode 9.4.1和Swift 4.1一起使用
答案 0 :(得分:1)
为什么不使用didSet
?
didSet {
if isSelecteda {
CustomView.backgroundColor = UIColor.white
CustomView.layer.borderColor = UIColor.black.cgColor
} else {
CustomView.backgroundColor = Colors.searchGameCellBackgroundColor
CustomView.layer.borderColor = Colors.priceLabelBorderColor?.cgColor
}
}
重置值为 的原因可能是因为您的变量仍然具有oldValue
,您将使用它在setter中进行比较。当您在setter中调用变量时,由于尚未设置oldValue
,因此getter将获得newValue
。
注意:最好遵循官方命名guidelines的命名约定。变量为小写驼峰。 CustomView
-> customView
。
答案 1 :(得分:1)
根据我的理解,您应该像这样更改设置器:
set {
_isSelecteda = newValue
if _isSelecteda {
CustomView.backgroundColor = UIColor.white
CustomView.layer.borderColor = UIColor.black.cgColor
}
else {
CustomView.backgroundColor = Colors.searchGameCellBackgroundColor
CustomView.layer.borderColor = Colors.priceLabelBorderColor?.cgColor
}
}
newValue 变量是调用设置器时收到的实际值。
何时执行此操作:
customView.isSelecteda = false
设置器在newValue变量中获取'false'。您可以将此值设置为私有变量,然后根据该值执行后续功能。
您可以在以下问题中找到有关“ oldValue”和“ newValue”的更多信息: Click Here
编辑:关于这是正确行为的理由:
get {
return _isSelecteda // false - from init call
}
set {
_isSelecteda = isSelecteda // isSelecteda getter called from above returning false, newValue is neglected
if _isSelecteda { // returns false
CustomView.backgroundColor = UIColor.white
CustomView.layer.borderColor = UIColor.black.cgColor
}
else {
CustomView.backgroundColor = Colors.searchGameCellBackgroundColor
CustomView.layer.borderColor = Colors.priceLabelBorderColor?.cgColor
}
}