Swift - UIButton 覆盖 setSelected [英] Swift - UIButton overriding setSelected

查看:24
本文介绍了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:

  1. 覆盖 willSet/didSet 的属性仍会为 get/set 调用 super.您可以判断,因为状态从 .normal 变为 .selected.
  2. willSet 和 didSet 即使值没有改变也会被调用,因此您可能希望将 selected 的值与 willSet 中的 newValue 进行比较oldValue 中的 didSet 来确定是否进行动画处理.
  1. Overriding a property for willSet/didSet still calls super for get/set. You can tell because the state changes from .normal to .selected.
  2. 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 either newValue in willSet or oldValue in didSet 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆