有没有办法禁用 SwiftUI 的文本自动孤立修复?

You*_*Dan 11 swift swiftui

我本质上正在构建一个记忆应用程序,点击键盘上的按钮从预定字符串中获取下一个单词,并将其添加到输出的文本中,如下所示:

struct TypingGameView: View {
   @State var text: String = "Some text that wraps at the incorrect spot and is quite annoying."
   @State var outputText: String = ""
   @State private var enteredText: String = ""
   @State private var wordsTapped = 0

   var body: some View {
      ZStack {
         TextField("", text: $enteredText)
            .onChange(of: enteredText) { newValue in
               addToOutputText(newValue)
            }
         Rectangle()
            .foregroundColor(.white)
         VStack {
            Text(outputText)
               .frame(maxWidth: .infinity, alignment: .leading)
               .padding()
            Spacer()
         }
      }
   }

   func addToOutputText(_ val: String) {
      let words = text.components(separatedBy: " ")

      for (index, word) in words.enumerated() {
         if index == wordsTapped {
            outputText += "\(word) "
            wordsTapped += 1
            return
         }
      }      
   }
}
Run Code Online (Sandbox Code Playgroud)

问题是,第一行的最后一个单词只有在后面还有一个单词时才会跳到下一行,但一旦后面有更多单词,就会跳回第一行。见下文:

自动孤立修复正在实施

据我所知,这是TextSwiftUI 中视图的自动功能,用于防止出现任何孤立单词。我想禁用此功能,因为它会使单词在我创建的视图中跳转。我已经看到了在 UIKit 中使用 a 的解决方案CATextLayer(请参阅UILabel 和 UITextView 换行符不匹配获取 UILabel 中的每一行文本),但我需要一些与 SwiftUI@State包装器一起使用的解决方案,并且更喜欢使用所有 SwiftUI 的解决方案。最终目标是获得与上述视频相同的功能,但没有自动孤儿修复。

编辑:刚刚尝试使用每个单词内部的Group单独视图。Text仍然做同样的事情:/

Jon*_*an. 4

扩展 Wamba 的答案。您可以使用零宽度空格,这样如果文本位于单行上,则其后面不会有可见空格,也不会换行到第三行。

/// This makes the text wrap so that it can have one word on the last line (a widow), by default iOS will leave an extra gap on the second to last line
/// and move the second to last word to the last line. With 2 line text this can make the text look like a column and make the UI look unbalanced.
public extension String {
    var fixWidow: String {
        self + "\u{200B}\u{200B}\u{200B}\u{200B}"
    }
}


// Use case:
Text("a short sentence that often wraps to two lines".fixWidow)
Run Code Online (Sandbox Code Playgroud)

这是一个 hack,我不喜欢它,但是应用程序用户看不到黑客代码,只有一个奇怪的 UI,所以在 Apple 最终为 SwiftUI 提供与 UIKit 相同的功能之前,这是更好的选择。