SwiftUI多行文本自动换行和连字符问题

13

我在使用 SwiftUI Text 时遇到了以下问题:

在下面的例子中,SwiftUI将单词“Amazement”分为第一行的“amazeme”和第二行的“nt”。如何避免这种情况,这是一个bug吗?

我希望单词“amazement”能够写在一行上。是否有任何修饰符可以实现这一点(不要拆分单词或其他)?

尝试过 .allowsTightening、.fixedSize,并更改修饰符的顺序,但没有帮助。

这是一个bug吗?还是我们目前没有选择来解决这个问题?该解决方案应适用于每个字符串,而不仅仅是提到的字符串。

您可以使用以下代码复制此行为:

 struct TestView2: View {
    var body: some View {
        ZStack {
        Text("Amazement Awaits us at every corner")
           
            .font(.system(size: 160))
            .foregroundColor(.blue)
            .foregroundColor(.white)
            .lineLimit(4)
            .multilineTextAlignment(.leading)
            .minimumScaleFactor(0.01)
            //.allowsTightening(true)
            //.fixedSize(horizontal: false, vertical: true)
      
        }
    }
}
    
    struct TestView2_Previews: PreviewProvider {
        static var previews: some View {
            TestView2()
        }
    }

文本连字问题的示例

2个回答

1

看起来在适应视图中的文本时,按字符换行是默认设置。我发现只有当系统无法适应文本(通过字符换行)时,.minimumScaleFactor 才能起作用。如果这样仍然不行,那么它将尝试缩小文本。如果您尝试减少 linelimit,那么 minimumScaleFactor 将开始工作,并尝试使文本变小,直到适应。

目前,我正在使用一个技巧,检查文本中单词的字符数,如果任何单词的字符数大于某个阈值,则减小字体大小,否则使用默认大小。

struct TestView2: View {
    let text: String
    var body: some View {
        ZStack {
            Text(self.text)
                .font(.system(size: self.getSizeForText(self.text)))
                .foregroundColor(.blue)
                .foregroundColor(.white)
            .lineLimit(4)
            .multilineTextAlignment(.leading)
            .minimumScaleFactor(0.01)
            //.allowsTightening(true)
            //.fixedSize(horizontal: false, vertical: true)
        }
    }
    
    private fund getSizeForText(_ text: String) -> Double {
        let CHARS_THRESHOLD = 12 // change this as needed
        let words = text.split(separator: " ")
        if words.contains(where: { $0.count > CHARS_THRESHOLD }) {
            // text contains a long word, decrease the font size
            return 150.0 // the smaller size, change as needed
        }
        // all words are shorter than the threshold
        return 160.0 // the default size, change as needed
    }
}

这种方法并不适用于所有情况,但希望它可以进行调整,直到苹果公司提供了一个适当的解决方案。我无法想象在没有连字符的情况下按字符打断单词是最佳解决方案的场景。

1

已修复:Xcode 13.3 / iOS 15.4

演示

Text("Amazement Awaits us at every corner")

    .font(.system(size: 460))   // << even such size (or any other big)
    .foregroundColor(.blue)
    .foregroundColor(.white)
    .lineLimit(4)
    .multilineTextAlignment(.leading)
    .minimumScaleFactor(0.01)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接