如何在 SwiftUI 中动态计算字符串的宽度

Jos*_*cis 4 ios swift swiftui

假设我有一个名为:的文本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#>)

}
}  
Run Code Online (Sandbox Code Playgroud)

Dav*_*pin 10

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

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

  • 那真是太精彩了!我正在搞乱 GeometryReady 和首选项(key:value :) 但没有成功。 (3认同)