ios - 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)
什么都没有改变!
知道为什么它不起作用吗?
解决方案
为什么要在扩展中创建属性?你甚至不需要吸气剂。恕我直言,最好创建一个方法。
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
,它是分配的当前值。
推荐阅读
- python - 在树莓派 3 上为 docker 安装 OpenCV
- python - Sympy 集成错误:无法将符号转换为 int
- python - 如何处理多个功能的过滤器?
- python - 如何使用 baggingregressor 进行特征选择?
- python - 如何根据python中的地图将rgb值转换为整数
- c++ - 带有地址但不引用地址的 C++ 指针
- asp.net-core - 在 RedirectToAction 之后运行后台任务
- javascript - 如何更新嵌套在 ReactJS 中的对象内的数组的属性
- google-app-engine - 有没有办法检测 AppEngine 中的版本是否为非默认版本?
- python - 使用 itertools 重复数字