【问题标题】:SwiftUI Word Wrap for multiline text Word Hyphenation ProblemSwiftUI Word Wrap 用于多行文本 Word 断字问题
【发布时间】:2020-09-07 19:56:10
【问题描述】:

我在使用 SwiftUI Text 时遇到以下问题: 在下面的示例中,SwiftUI 将单词“Amazement”分解为第一行的“amazeme”和第二行的“nt”。怎么避免,是不是bug?

我希望将“惊奇”一词写在一行上。 是否有任何修饰符可以允许这样做(不要分词或其他东西)?

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

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

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

 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()
        }
    }

【问题讨论】:

    标签: swift text swiftui ios14 swiftui-text


    【解决方案1】:

    在视图中调整文本时,按字符换行似乎是默认设置。我发现.minimumScaleFactor 仅在系统无法适应文本(带有字符中断)时才有效。如果这不起作用,那么它将尝试缩小文本。如果您尝试减小linelimit,那么minimumScaleFactor 将启动并尝试使文本更小,直到适合为止。

    目前我正在使用 hack 来检查文本中单词的字符数,如果任何单词的字符数超过某个阈值,那么我会减小字体大小,否则我使用默认大小。

    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
        }
    }
    

    这不适用于所有场景,但希望它可以调整,直到 Apple 提出适当的解决方案,因为我无法想象在没有连字符的情况下按字符分词是最佳解决方案的场景。

    【讨论】:

      猜你喜欢
      • 2011-03-17
      • 1970-01-01
      • 2022-01-15
      • 2012-05-31
      • 1970-01-01
      • 2016-05-17
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多