【问题标题】:How to figure out the width of a string dynamically in SwiftUI如何在 SwiftUI 中动态计算字符串的宽度
【发布时间】:2019-11-10 02:45:11
【问题描述】:

假设我有一个名为:This 的文本。我想弄清楚名为This 的文本的宽度,以便我可以为另一个视图的框架分配宽度。我该怎么办?

struct BadgeTextView: View {

var text: String

var body: some View {
    Rectangle()
        .fill(Color.red)
    .cornerRadius(3)
        .frame(width: text.???, height: <#T##CGFloat?#>, alignment: <#T##Alignment#>)

}
}  

【问题讨论】:

  • "Width" 不是字符串的固有属性。确定字符串的宽度需要字体和字体大小。只要确保你也考虑到这一点。

标签: ios swift swiftui


【解决方案1】:

String 的这个扩展应该建立在 Sweeper 的建议之上,让您获得 String 的宽度给定某种字体

extension String {
   func widthOfString(usingFont font: UIFont) -> CGFloat {
        let fontAttributes = [NSAttributedString.Key.font: font]
        let size = self.size(withAttributes: fontAttributes)
        return size.width
    }
}

这将像这样使用:let width = "SomeString".widthOfString(usingFont: UIFont.systemFont(ofSize: 17, weight: .bold))

【讨论】:

  • 太棒了!我在搞乱 GeometryReady 和 preference(key:value:) 没有成功。
  • 我使用 Courier 因为它是等宽的。 “1”重复36次的字符串的宽度是257.34375,而36个“M”的字符串是492.1875。因为它是等宽的,所以这些宽度不应该相同吗?
猜你喜欢
  • 2010-12-04
  • 1970-01-01
  • 2012-10-12
  • 1970-01-01
  • 1970-01-01
  • 2019-04-08
  • 1970-01-01
  • 2018-11-28
  • 1970-01-01
相关资源
最近更新 更多