【问题标题】:SwiftUI offset Text() by font sizeSwiftUI 按字体大小偏移 Text()
【发布时间】:2020-12-24 08:29:17
【问题描述】:

我怎样才能偏移一个文本,以便在字符中间完全分割。我面临的问题是角色没有很好地分割。到目前为止我所拥有的:

Text("8")
    .font(.system(size: size, design: fontDesign))
    .foregroundColor(fontColor)
    .offset(x: 0, y: size/2)
    .frame(width: size, height: size/2, alignment: .bottom)
    .background(Color.black)
    .clipShape(Rectangle())

Text("8")
    .font(.system(size: size, design: fontDesign))
    .foregroundColor(fontColor)
    .offset(x: 0, y: -size/2)
    .frame(width: size, height: size/2, alignment: .top)
    .background(Color.black)
    .clipShape(Rectangle())

这会产生以下输出:

我知道我可以调整偏移量以使其很好地对齐(如果 size=50,y 偏移量将是 36-36 来对齐)。但是,size 必须是可变的。如何做到这一点?

【问题讨论】:

  • size是针对字体的,这并不意味着它会等于视图大小,你需要计算view size

标签: swift swiftui


【解决方案1】:

这是一个似乎有效的示例。对于每个 Text(),将帧设置为 100%,然后添加第二帧,将第一帧切成两半并对齐到 .top / .bottom。

struct AlignmentTest: View {
    
    let size: CGFloat = 36
    let fontDesign = Font.Design.default
    let fontColor = Color.black
    let lineHeight: CGFloat = 100
    let text: String = "This is a TEST run! 888"
    
    var body: some View {
        VStack(spacing: 0) {
            Text(text)
                .font(.system(size: size, design: fontDesign))
                .foregroundColor(fontColor)
                .frame(height: lineHeight / 2) // frame1: Set height @ 100%
                .background(Color.red)
                .frame(height: lineHeight / 4, alignment: .top) // frame2: Cut frame1 half & align to top
                .clipped() // Clip result to frame2

            Text(text)
                .font(.system(size: size, design: fontDesign))
                .foregroundColor(fontColor)
                .frame(height: lineHeight / 2)
                .background(Color.blue)
                .frame(height: lineHeight / 4, alignment: .bottom)
                .clipped()
        }
    }
}

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    相关资源
    最近更新 更多