Swift - UIButton overriding setSelected(Swift - UIButton 覆盖 setSelected)
问题描述
我正在 Swift 中创建一个 UIButton 子类,以在选择时执行自定义绘图和动画
I'm making a UIButton subclass in Swift to perform custom drawing and animation on selection
在 Swift 中,在 ObjC 中覆盖 - (void)setSelected:(BOOL)selected
的等价物是什么?
What would be the equivalent in Swift of overriding - (void)setSelected:(BOOL)selected
in ObjC?
我试过了
覆盖 var selected: Bool
所以我可以实现一个观察者,但我得到了
so I could implement an observer but I get
不能用存储的属性'selected'覆盖
推荐答案
和其他人提到的一样,您可以使用 willSet
来检测更改.但是,在覆盖中,您不需要将值分配给 super,您只是在观察现有的更改.
Like others mentioned you can use willSet
to detect changes. In an override, however, you do not need assign the value to super, you are just observing the existing change.
您可以从以下游乐场观察到几件事:
A couple things you can observe from the following playground:
- 覆盖
willSet/didSet
的属性仍会为get/set
调用 super.您可以判断,因为状态从.normal
变为.selected
. - willSet 和 didSet 即使值没有改变也会被调用,因此您可能希望将
selected
的值与willSet 中的
或newValue
进行比较oldValue
中的didSet
来确定是否进行动画处理.
- Overriding a property for
willSet/didSet
still calls super forget/set
. You can tell because the state changes from.normal
to.selected
. - willSet and didSet are called even when the value is not changing, so you will probably want do the compare the value of
selected
to eithernewValue
inwillSet
oroldValue
indidSet
to determine whether or not to animate.
import UIKit
class MyButton : UIButton {
override var isSelected: Bool {
willSet {
print("changing from (isSelected) to (newValue)")
}
didSet {
print("changed from (oldValue) to (isSelected)")
}
}
}
let button = MyButton()
button.state == .normal
button.isSelected = true // Both events fire on change.
button.state == .selected
button.isSelected = true // Both events still fire.
这篇关于Swift - UIButton 覆盖 setSelected的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Swift - UIButton 覆盖 setSelected
基础教程推荐
- 更改 UITableView 部分标题的颜色 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- EditText 中的 setHintTextColor() 2022-01-01
- UINavigationItem 的持久 rightBarButtonItem 属性 2022-01-01
- Android - 如何在runOnUiThread 中将数据传递给Runnable? 2022-01-01
- 从 UIWebView 访问元数据 2022-01-01
- 在 iOS 7 下 CCMenu 错位 2022-01-01
- UINavigationBar 隐藏按钮文本 2022-01-01
- Firebase 云消息传递令牌未生成 2022-01-01
- 在视图控制器的宽度上水平均匀分布 UIButton 的最简单方法? 2022-01-01