SwiftUI外观动画

时间:2020-08-20 13:47:47

标签: ios swift animation swiftui swiftui-animation

我正在使用出现在动画屏幕上的屏幕键盘。我的ButtonStyle定义如下:

struct KeyboardSquareButtonStyle: ButtonStyle {
    var enabledColor: Color = Color.AppColor.Keyboard.regularButtonActive
    var disabledColor: Color = Color.AppColor.Keyboard.regularButtonInactive
    
    func makeBody(configuration: Self.Configuration) -> some View {
        ConfigurationWrappedKeyboardButton(configuration: configuration, enabledColor: enabledColor, disabledColor: disabledColor)
            .aspectRatio(1, contentMode: .fit)
    }
}

struct ConfigurationWrappedKeyboardButton: View {
    let configuration: KeyboardRectangleButtonStyle.Configuration
    var enabledColor: Color
    var disabledColor: Color
    
    @Environment(\.isEnabled) private var isEnabled: Bool
    
    var body: some View {
        configuration.label
            .font(Font.system(size: 50, weight: .light, design: .default))
            .foregroundColor(Color.AppColor.primaryText)
            .frame(minWidth: 45, maxWidth: .infinity, minHeight: 45, maxHeight: .infinity, alignment: .center)
            .background(backgroundColor(pressed: configuration.isPressed))
            .animation(.easeOut(duration: 0.1))
    }
    
    private func backgroundColor(pressed: Bool) -> Color {
        guard !pressed else {
            return enabledColor.opacity(0.7)
        }
        
        return isEnabled ? enabledColor : disabledColor
    }
}

动画按钮状态对我来说至关重要。

键盘是一个HStack,其中包含两个VStack,它们都有自己的外观转换:

struct Example: View {
    @State private var keyboardShown: Bool = false
    
    var body: some View {
        ZStack {
            VStack {
                Button("Toggle keyboard") { self.keyboardShown.toggle() }
                Spacer()
            }
            
            if keyboardShown {
                Keyboard()
                    .transition(.move(edge: .leading))
                    .animation(.easeIn)
            }
        }
    }
}

struct Keyboard: View {
    var body: some View {
        HStack(spacing: 1) {
            VStack(spacing: 1) {
                Button("Button") {}
                Color.green
            }
            
            VStack(spacing: 1) {
                Color.blue
                Color.yellow
            }
        }
        .buttonStyle(KeyboardSquareButtonStyle())
        .aspectRatio(1, contentMode: .fit)
    }
}

以上代码如果功能完整,可以启动进行测试。我现在的实际结果是,当Button忽略父animation设置并使用ButtonStyle中指定的animation进行父转换时,三个彩色视图以相同的速度和过渡出现。有没有办法让ButtonStyle逻辑不影响整个键盘外观的转换?

0 个答案:

没有答案