首页 > 解决方案 > 根据布局方向翻转 SwiftUI Shape

问题描述

我制作了一个 SemiRoundedRectangle 形状,我用它来裁剪侧边菜单。如果用户使用 RTL 语言,我需要翻转它,但不确定实现这一点的最佳方法。

我试过.flipsForRightToLeftLayoutDirection(true)了,但这也翻转了实际的阿拉伯语文本。当我尝试旋转形状时,它不再符合 Shape 协议,因此我不能再在.clipShape. 当我切换到阿拉伯语时,SwiftUI 中的其他所有东西都会神奇地自行翻转,我可以在我的形状中添加一些东西来赋予它这些魔力吗?

谢谢你的帮助 :)


import SwiftUI

struct SemiRoundedRectangle: Shape {
    var cornerRadius: CGFloat
    func path(in rect: CGRect) -> Path {
        var path = Path()
        path.move(to: CGPoint(x: rect.maxX, y: rect.minY))
        path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
        path.addLine(to: CGPoint(x: rect.minX+cornerRadius, y: rect.maxY))
        path.addArc(center: CGPoint(x: cornerRadius, y: rect.height - cornerRadius),
                    radius: cornerRadius,
                    startAngle: .degrees(90),
                    endAngle: .degrees(180), clockwise: false)
        path.addLine(to: CGPoint(x: 0, y: cornerRadius))
        path.addArc(center: CGPoint(x: cornerRadius, y: cornerRadius),
                    radius: cornerRadius,
                    startAngle: .degrees(180),
                    endAngle: .degrees(270), clockwise: false)
        path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
        
        return path
    }

}

struct TestView {
    var body: some View {
        HStack {
            Text("ايه الأخبار؟")
            .padding()
            .background(Color.green)
            .clipShape(SemiRoundedRectangle(cornerRadius: 10.0))
            
            Spacer()
        }
        
    }
}

标签: iosswiftswiftuilocalization

解决方案


尝试将其附加clipShapeColor.green

struct TestView: View {
    var body: some View {
        HStack {
            Text("ايه الأخبار؟")
            .padding()
            .background(
                Color.green /// here!
                    .clipShape(SemiRoundedRectangle(cornerRadius: 10.0))
                    .flipsForRightToLeftLayoutDirection(true)
            )
            
            Spacer()
        }
    }
}

结果:

英语 RTL 语言
左角为圆形的绿色矩形,位于屏幕左侧 右上角为圆形的绿色矩形,位于屏幕右侧

推荐阅读