【问题标题】:How to have text fit within boundaries of circular shape/image SwiftUI如何使文本适合圆形/图像SwiftUI的边界
【发布时间】:2021-04-09 23:36:22
【问题描述】:

我似乎无法掌握如何确保我的文本覆盖并适合圆形图像的边界。这是我目前所拥有的。

Circle()
    .frame(width: 100, height: 100)
    .overlay(
        Text("Reaaaallllllyyyyyy Looooooongggggg")
            .foregroundColor(Color.red)
            .frame(minWidth: 0, maxWidth: .infinity)
        )

在 SwiftUI 中有没有办法让它工作?我将如何实现这一目标?

【问题讨论】:

标签: swift swiftui swiftui-text


【解决方案1】:
struct ClippedCircleView: View {
    @State var text: String = "Reaaaallllllyyyyyy Looooooongggggg"
    // Make this any number you are comfortable with
    @State var letterLimit: Int = 12
    var body: some View {
        
        Circle()
            .frame(width: 100, height: 100)
            .overlay(
                Text(text)
                    //Limit to 1 line until your letterLimit
                    .lineLimit(text.count <= letterLimit ? 1 : nil)
                    //Clips it to shape
                    .clipShape(ContainerRelativeShape()).padding()
                    .foregroundColor(Color.red)
                    //This makes super tiny letters so adjust to your use case
                    .minimumScaleFactor(0.1)
                
            )
    }
}

【讨论】:

  • 这对我有用。对于示例中的长字符串,如果字符串超过一定长度,您会缩小字体吗?这样它就适合一行。
  • 您可以,只需将.linelimit 设置为您想要的长度。查看代码。
猜你喜欢
  • 2018-07-07
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
  • 2021-03-05
  • 1970-01-01
  • 2023-02-03
  • 1970-01-01
相关资源
最近更新 更多