我正在尝试使用 xib 创建自定义视图 下面是代码
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的私有声明并重置值。我的目标是从视图控制器中设置 isSelected 的值并更改其背景颜色。
根据我的理解,情况不应该是这样。它很奇怪
注意:我正在使用 Xcode 9.4.1 和 Swift 4.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
}
}
重置值的原因可能是因为您的变量仍然具有您在 setter 内部用于比较的oldValue
。当您在 setter 中调用变量时,getter 会获得oldValue
,因为尚未设置newValue
。
注意:最好遵循官方命名指南中的命名约定。变量为小驼峰大小写。CustomView
->customView
.
根据我的理解,您应该像这样更改二传手:
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变量是调用 setter 时接收的实际值。
当您执行此操作时:
customView.isSelecteda = false
setter 在 newValue 变量中得到 'false'。将此值设置为私有变量,并根据此值执行后续函数。
您可以在此问题中找到有关"oldValue"和"newValue"的更多信息: 点击这里
编辑:关于这是正确行为的理由:
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
}
}