如何创建两个大小相同的文本视图

时间:2020-10-16 19:44:30

标签: swiftui

我正在开发一个游戏,并且有一些文字视图,它们表示可以翻转的纸牌。卡的两边都有文字。我希望卡片的每一面都一样大小。也就是说,我希望文字较少的一面的卡片与文字较多的那张卡片的大小相同。我不想对卡的大小进行硬编码,因为有时只有一行文本,而有时会有多行文本。这是我当前拥有的代码的摘录:

import SwiftUI

struct FlipTestView: View {
    
    @State var flipped = false
    
    var body: some View {
        let flipDegrees = flipped ? 180.0 : 0
        VStack {
            ZStack() {
                Text("Card One First Side Of Card")
                    .placedOnCard(Color.yellow)
                    .flipRotate(flipDegrees).opacity(flipped ? 0.0 : 1.0)
                Text("""
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                    """)
                    .placedOnCard(Color.green)
                    .flipRotate(-180 + flipDegrees).opacity(flipped ? 1.0 : 0.0)
            }
            .animation(.easeInOut(duration: 0.8))
            .onTapGesture { flipped.toggle()}
        }
    }
}

struct FlipTestView_Previews: PreviewProvider {
    static var previews: some View {
        FlipTestView()
    }
}

extension View {
    
    func flipRotate(_ degrees : Double) -> some View {
        return rotation3DEffect(Angle(degrees: degrees), axis: (x: 1.0, y: 0.0, z: 0.0))
    }
    
    func placedOnCard(_ color: Color) -> some View {
        return
            padding(15)
            //            .frame(width: 350, height: 65, alignment: .center).background(color)
            .background(color)
            .cornerRadius(16)
            .overlay(
                RoundedRectangle(cornerRadius: 16)
                    .stroke(Color.blue, lineWidth: 4)
            )
    }
}

1 个答案:

答案 0 :(得分:2)

.placedOnCard移到包含两面的ZStack上,然后将其大小调整为两面中较大的一个。这是重构代码的解决方案:

ZStack() {
    Text("Card One First Side Of Card")
        .opacity(flipped ? 0.0 : 1.0)
    Text("""
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        """)
        .flipRotate(180.0).opacity(flipped ? 1.0 : 0.0)
}
.placedOnCard(flipped ? Color.green : Color.yellow)
.flipRotate(flipDegrees)
.animation(.easeInOut(duration: 0.8))
.onTapGesture { flipped.toggle()}

demo of card flip in simulator