SwiftUI Text scaledToFit 和换行

Posted

技术标签:

【中文标题】SwiftUI Text scaledToFit 和换行【英文标题】:SwiftUI Text scaledToFit and wrap text 【发布时间】:2021-07-08 00:29:24 【问题描述】:

我有一个带有动态文本的按钮。我希望缩小文本以适应它(尽可能),并将文本换行到一定数量的行(可能是 2 行?)。

默认情况下,SwiftUI 似乎将文本包裹在单词上。但似乎当我在 Text 视图上使用 scaledToFit 修饰符时,它会阻止单词换行。

这里有一些操场代码来说明:

import SwiftUI
import PlaygroundSupport

struct ContentView: View 
  var body: some View 

    let lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

    VStack 

      // Here is the default text - see in the screenshot that it properly wraps the text
      HStack 
        Text(lorem)
      
      .frame(width: 100, height: 100)
      .background(Color.blue)

      // Here is text that is scaled down, but prevented from wrapping, even though 
      // we have allowed it to use 2 lines.
      HStack 
        Text(lorem)
          .allowsTightening(true)
          .scaledToFit()
          .lineLimit(2)
          .minimumScaleFactor(0.7)
      
      .frame(width: 100, height: 100)
      .background(Color.green)

      // Here is the text with the same scaling modifiers as above, but it
      // is still set to the original font size
      HStack 
        Text("Short")
          .allowsTightening(true)
          .scaledToFit()
          .lineLimit(2)
          .minimumScaleFactor(0.7)
      
      .frame(width: 100, height: 100)
      .background(Color.pink)

    
  


PlaygroundPage.current.setLiveView(ContentView())

因此,理想情况下,我想要第一个和第二个视图的组合 - 我希望文本换行,但如果文本不能立即适合父视图,我也会缩小到某个最小尺寸。

【问题讨论】:

更改字体,而不是 scaledToFit。如果您使用.font(.headline) 或任何其他system standard font,您可以免费获得缩放。 【参考方案1】:

试试这个,粉色也一样:

    HStack 
        Text(lorem)
            .frame(width: 100, height: 100)  // <--- here
            .allowsTightening(true)
            .lineLimit(2)
            .scaledToFit()
            .minimumScaleFactor(0.7)
    
    .frame(width: 100, height: 100)
    .background(Color.green)

【讨论】:

以上是关于SwiftUI Text scaledToFit 和换行的主要内容,如果未能解决你的问题,请参考以下文章

SwiftUI中的GLKView?

SwiftUI Image scaledToFill 布局行为

SwiftUI GeometryReader 不会在中心布局自定义子视图

SwiftUI 中图像按钮的可点击区域

如何使用 SwiftUI 实现已裁剪为形状的缓慢滑动图像?

SwiftUI 全屏图片背景