首页 > 解决方案 > UIView 扩展中用于自定义枚举案例的新属性

问题描述

我正在尝试在 UIView 上应用一些案例,例如通过为新颜色设置动画来更改颜色或平滑隐藏视图

在这里,我创建了一个小枚举来保存我所有的动画案例:

enum ViewAnimation {
    case changeColor(to: UIColor, duration: TimeInterval)
    case hideView(duruation: TimeInterval)
}

在这里,我想为 UIView 创建一个属性:

extension UIView {


var animate: ViewAnimation {
    get {
        return .changeColor(to: .red, duration: 1) // actually I don't know what to add in the getter !
    }
    set {
        switch self.animate {
        case .changeColor(let newColor, let duration):
            UIView.animate(withDuration: duration) {
                self.backgroundColor = newColor
            }
        case .hideView(let duration):
            UIView.animate(withDuration: duration) {
                self.alpha = 0
                self.isHidden = true
            }
        }
    }
}

}

这是我的课:

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    let smallView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    view.addSubview(smallView)
    smallView.backgroundColor = .red
    smallView.center = view.center

    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
        smallView.animate = .changeColor(to: .blue, duration: 3)
    }
}
}

问题是当我打电话时smallView.animate = .changeColor(to: .blue, duration: 3)什么都没有改变!

知道为什么它不起作用吗?

标签: iosswift

解决方案


为什么要在扩展中创建属性?你甚至不需要吸气剂。恕我直言,最好创建一个方法。

extension UIView {
    func animate(animation: ViewAnimation) {
        switch animation {
        case .changeColor(let newColor, let duration):
            UIView.animate(withDuration: duration) {
                self.backgroundColor = newColor
            }
        case .hideView(let duration):
            UIView.animate(withDuration: duration) {
                self.alpha = 0
                self.isHidden = true
            }
        }
    }
}

并称它为smallView.animate(animation: .changeColor(to: .blue, duration: 3))

但是,如果您真的想使用该属性,则不能这样做,switch self.animate因为它会调用 getter。尝试这样做switch newValue,因为每个set都有一个名为的隐式局部变量newValue,它是分配的当前值。


推荐阅读