gpt4 book ai didi

swift - 简化 UIView 动画 if/else

转载 作者:行者123 更新时间:2023-11-30 12:12:48 25 4
gpt4 key购买 nike

iOS UIKit 库中的许多回调和方法都有一个 animated bool 值,表示某个操作是否应该设置动画,或者只是设置。

一个这样的例子是这个方法:

UITableViewCell.setSelected(_ selected: Bool, animated: Bool)

假设我想在选择时更改 textLabel 文本颜色和单元格的背景颜色。我目前正在做这样的事情:

override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)

let bgColor = !selected ? UIColor.clear : UIColor.blue
let textColor = !selected ? UIColor.black : UIColor.white

if !animated {
self.textLabel?.textColor = textColor
self.backgroundColor = bgColor
} else {
UIView.animate(withDuration: 0.1) {
self.textLabel?.textColor = textColor
self.backgroundColor = bgColor
}
}
}

很简单,我计算出新的颜色值,然后应用它们。

这里令人沮丧的部分是我必须检查我们是否正在制作动画,以及是否将 setter 包装在动画 block 中。这感觉真的很难看,如果您所做的不仅仅是改变背景颜色,情况会更糟。

我确信其他人已经很好地解决了这个问题,所以我想知道你们(和女孩)是如何做到的?

最佳答案

创建一个函数来处理您想要更改的任何内容,例如,

    func updateTheme(selected: Bool) {
self.textLabel?.textColor = !selected ? UIColor.clear : UIColor.blue
self.backgroundColor = !selected ? UIColor.black : UIColor.white
}

然后在你的主函数中调用它

    override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
UIView.animate(withDuration: selected ? 0.1 : 0) {
self.updateTheme(selected: selected)
}
}

或者

   override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)

if !animated {
updateTheme(selected: selected)
} else {
UIView.animate(withDuration: 0.1) {
self.updateTheme(selected: selected)
}
}
}

关于swift - 简化 UIView 动画 if/else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45846468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com