Text当有多行时,SwiftUI 的视图存在问题。所以只要看看:
var body: some View {
Text("Some word Some word Some word Some word")
.frame(maxWidth: .infinity, alignment: .leading)
.border(.red)
.padding(16)
}
Run Code Online (Sandbox Code Playgroud)
然而添加一个词改变了包装:
结果,视图看起来不像预期的那样,对于更大的字体,差异变得更加明显:
环境:iOS 15.2、Xcode 13 / Xcode 14b 预览和模拟器
UILabel是否有可靠的解决方案可以像不使用 那样包装字符串UIViewRepresentable?
PS:.fixedSize()已经尝试了+的不同组合.frame(idealWidth:),但没有运气
Mar*_*rcy 10
Apple 遵循排版规则。其中一条规则是避免在段落的最后一行出现单个单词。由于所有的空白,这种所谓的矮字被认为会分散读者的注意力。但是,如果最后一个单词和任何尾随标点符号超过 10 个字符,则此规则不适用。
据我所知,不存在直接关闭此规则的选项。但解决方法是在可能发生这种情况的文本末尾使用尾随空格。使用足够的尾随空格使最后一行的字符数超过 10 个。
使用您的示例,添加 7 个尾随空格即可。“Some”加上 7 个空格共 11 个字符:
Text("Some word Some word Some word Some word Some ")
Run Code Online (Sandbox Code Playgroud)
在此示例中,8 个尾随空格有效。“the”加上 8 个空格提供 11 个字符,因此该规则不适用,并且在需要的地方换行:
Text("Some word to demonstrate the ")
Run Code Online (Sandbox Code Playgroud)
有了尾随空格,布局在较大的设备上以及方向发生变化时看起来应该没问题。幸运的是,尾随空格被截断,不会自行创建新行。
extension String {
var padded: String { self + " " }
}
Run Code Online (Sandbox Code Playgroud)
用法:
Text("Some word to demonstrate the".padded)
Run Code Online (Sandbox Code Playgroud)
旁注:UILabel(版本 13.0、16.1)似乎也默认使用这些排版规则。但是 UILabel 可以通过换行策略设置关闭此排版规则:
label.lineBreakStrategy = NSParagraphStyle.LineBreakStrategy()
Run Code Online (Sandbox Code Playgroud)
或者像这样:
label.lineBreakStrategy = []
Run Code Online (Sandbox Code Playgroud)
但它似乎还没有在 SwiftUI 中可用。
| 归档时间: |
|
| 查看次数: |
1317 次 |
| 最近记录: |