我认为 View.disabled(_:)
修饰符改变了 View
的 .foregroundColor
(除了启用/禁用与它)。颜色变化可以动画化吗?
我知道用隐式动画(例如:.animation(.default)
)为 .opacity
变化设置动画非常容易。但是,同样不适用于 .disabled
。
请考虑以下代码:
import SwiftUI
struct SomeButton: View {
@State var isDisabled = false
@State var isHidden = false
var body: some View {
VStack(spacing: 30) {
Spacer()
Button(action: {}) {
Image(systemName: "pencil.circle.fill")
.resizable()
}
.frame(width: 80, height: 80)
.disabled(isDisabled) // 👈🏻 Will not animate at all.
.opacity(isHidden ? 0 : 1) // 👈🏻 Will animate just fine.
.animation(.default) // 👈🏻 Set to use implicit animations.
VStack(spacing: 10) {
Button(action: {
self.isHidden.toggle()
}) {
Text("Hide")
}
Button(action: {
self.isDisabled.toggle()
}) {
Text("Disable")
}
}
Spacer()
}
}
}
// MARK: - Preview
#if DEBUG
struct SomeButton_Previews: PreviewProvider {
static var previews: some View {
SomeButton()
}
}
#endif
这会产生以下结果,呈现平滑的不透明度过渡:
...另一方面,启用/禁用的颜色转换是二进制的。看起来不太好。
我目前的解决方法是根据 View 的启用/禁用状态更改 View 的不透明度。 因此,例如,如果 View 被禁用,则不透明度为 0.6。如果启用,不透明度将回到 1.0。
但是感觉不对。必须有另一种方法。
最佳答案
可能的解决方案是结合.colorMultipy
,当然disabled的颜色应该是实验性的合适,但这给出了通用的动画效果
.disabled(isDisabled)
.colorMultiply(isDisabled ? // 👈🏻 animatable
Color.gray /* to be selected to fit*/ : .white)
.animation(.default, value: isDisabled)
关于swift - SwiftUI的 ".disabled"修饰符的变化可以动画吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62191681/