SwiftUI 条件 .frame 视图修饰符

SwiftUI Conditional .frame View Modifier

我的代码如下:

Rectangle()
    .fill(Color.red)
    .frame(width: 60, height: 60, alignment: .center)
    .cornerRadius(recording ? 5 : 30)

所以我想知道 .frame 是否可以像 .cornerRadius 一样是有条件的。我这样做是为了变形形状,但是我还需要在变形时将其变小。一个例子是语音备忘录应用程序的录音按钮。

是的,您也可以将三元条件语句与 .frame 一起使用。

示例:

.frame(width: recording ? 40 : 60, height: recording ? 40 : 60, alignment: .center)

如果您正在谈论完全不使用框架修改器(或提供一种干净的方式来制作不同的框架),ViewModifier 可能是一个不错的选择:

struct ContentView: View {
    @State private var recording = false
    
    var body: some View {
        Rectangle()
            .fill(Color.red)
            .modifier(CustomFrameModifier(active: recording))
            .cornerRadius(recording ? 5 : 30)
    }
}

struct CustomFrameModifier : ViewModifier {
    var active : Bool
    
    @ViewBuilder func body(content: Content) -> some View {
        if active {
            content.frame(width: 60, height: 60, alignment: .center)
        } else {
            content
        }
    }
}

我假设你想要这样的东西

        Rectangle()
            .fill(Color.red)
            .frame(width: recording ? 45 : 60, height: recording ? 30 : 60, alignment: .center)
            .cornerRadius(recording ? 5 : 30)
            .onTapGesture {
                recording.toggle()
            }
            .animation(.default, value: recording)

你可以用 ?


import SwiftUI

struct ContentView: View {
    
    @State private var recording: Bool = Bool()
    @State private var color: Color = Color.blue
    
    var body: some View {
        
        ZStack {
            
            Circle()
                .fill(Color.white)
                .frame(width: 60.0, height: 60.0, alignment: .center)
                .shadow(radius: 10.0)
            
            Circle()
                .fill(color)
                .frame(width: recording ? 30.0 : 60.0, height: recording ? 30.0 : 60.0, alignment: .center)  // <<: Here!

 
        }
        .onTapGesture { recording.toggle() }
        .animation(.easeInOut, value: recording)
        .onChange(of: recording) { newValue in if newValue { colorFunction() } else { color = Color.blue } }

    }
    
    
    func colorFunction() {

        if (color != Color.red) { color = Color.red } else { color = Color.clear }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { if recording { colorFunction() } }
        
    }
    
}