版本: Xcode 12.3
我的项目大量使用UISwitch
。因此,我正在创建一个自定义类来自定义它。
我希望设置UISwitch
默认thumbTintColor
和backgroundColor
,并在打开开关时更新这些颜色(isOn
属性)。
我找到了一个解决方案,但当我返回到viewController
时,它就不起作用了。开关不保留设置:
subviews[0].subviews[0].backgroundColor = UIColor.white
我不能设置isOn
,因为它是只读属性。
无论如何,我可以设置值更改吗?我想在customSwitch类中得到如下所示:
关闭: thumbTintColor = UIColor.yellow,backgroundColor = UIcolor.black
接通: thumbTintColor = UIColor.red,backgroundColor = UIcolor.white
下面是我的定制课,有人能帮忙吗?谢谢。
import Foundation
@IBDesignable
class CustomSwitch: UISwitch {
private var previousValue = false
private var returnPreviousValue = false
override var isOn: Bool {
return returnPreviousValue ? previousValue : super.isOn
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
previousValue = isOn
addTarget(self, action: #selector(_didChange), for: .valueChanged)
}
override init(frame: CGRect) {
super.init(frame: frame)
addTarget(self, action: #selector(_didChange), for: .valueChanged)
}
override func setOn(_ on: Bool, animated: Bool) {
super.setOn(on, animated: animated)
previousValue = on
}
@objc func _didChange() {
let isOn = self.isOn
if isOn == previousValue {
return
}
returnPreviousValue = true
willChangeValue(forKey: "on")
returnPreviousValue = false
previousValue = isOn
didChangeValue(forKey: "on")
}
}
发布于 2021-06-04 08:54:02
代码
@IBDesignable
class CustomSwitch: UISwitch {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialSetUp()
}
convenience init() {
self.init(frame: .zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initialSetUp()
}
private func initialSetUp() {
self.addTarget(self, action: #selector(refreshUI), for: .valueChanged)
self.refreshUI()
}
@objc private func refreshUI() {
/// Be aware that this is more of a hack than a solution
/// And can break in any upcoming release
let targetSubview = self.subviews.first?.subviews.first
if self.isOn {
self.thumbTintColor = .red
targetSubview?.backgroundColor = .white
}
else {
self.thumbTintColor = .yellow
targetSubview?.backgroundColor = .black
}
}
}
用法
let customSwitch = CustomSwitch()
self.view.addSubview(customSwitch)
customSwitch.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
customSwitch.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
customSwitch.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
])
https://stackoverflow.com/questions/67833569
复制相似问题