SwiftUI Word Wrap for multiline text Word Hyphenation Problem

Ade*_*aer 5 text swift swiftui swiftui-text ios14

I'm facing the following problem with SwiftUI Text: In the following example SwiftUI breaks the word "Amazement" into "amazeme" on the first line and "nt" on the second. How to avoid it, isn't it a bug?

I want the word "amazement" to be written on one line. Is there any modifier that can allow this (don't divide words or something)?

Tried .allowsTightening, .fixedSize. Changed the order of modifiers, Didn't help.

Is it a bug or we currently don't have an option to fix this? The solution should work for every String, not only for the mentioned string.

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

 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()
        }
    }
Run Code Online (Sandbox Code Playgroud)

文本断字问题示例

Mot*_*sim 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
    }
}
Run Code Online (Sandbox Code Playgroud)

这并不适用于所有场景,但希望它是可以调整的,直到苹果提出一个适当的解决方案,因为我无法想象按字符打破单词甚至没有连字符的场景是最好的解决方案。