ios - Swift - UIButton 覆盖 setSelected

标签 ios swift uibutton subclass

我正在 Swift 中创建一个 UIButton 子类以在选择时执行自定义绘图和动画

在 Swift 中重写 ObjC 中的 - (void)setSelected:(BOOL)selected 有什么等价物?

我试过了

override var selected: Bool

所以我可以实现一个观察者但是我得到了

不能用存储属性“selected”覆盖

最佳答案

像其他人提到的那样,您可以使用 willSet 来检测更改。然而,在重写中,您不需要将值赋给 super,您只是观察现有的变化。

您可以从以下 Playground 观察到几件事:

  1. 覆盖 willSet/didSet 的属性仍然会为 get/set 调用 super。您可以看出,因为状态从 .normal 更改为 .selected
  2. willSet 和 didSet 即使值没有改变也会被调用,因此您可能希望将 selected 的值与 willSet 中的 newValue 进行比较didSet 中的 oldValue 来决定是否动画。
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.

关于ios - Swift - UIButton 覆盖 setSelected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26364869/

相关文章:

php - Swift 3 上传图像到 PHP 失败

ios - 我的 UIView 有一个 UIButton 作为它的 subview 之一,但不响应 Objective-C 中的事件

ios - 为什么这本字典中的值会改变?

ios - 如何从一个类调用另一个类的方法(iOS)

iOS:使用 Word Wrap 以编程方式创建标签

ios - 如何解决 CGPath 性能不佳的问题? [iOS 8/SpriteKit 中的 Curve Fever 克隆]

ios - 尝试使用图像和文本创建 UIButton 时出现奇怪的结果

ios - 有人见过 Interface Builder 属性 'Opaque' 和 'Clears Graphics Context' 起作用吗?

objective-c - keysSortedByValueUsingComparator 没有给出正确排序的数组

ios - 调用 UIApplication 子类方法启动 scheduledTimer