如何在 SwiftUI 中动态计算字符串的宽度 [英] How to figure out the width of a string dynamically in SwiftUI
本文介绍了如何在 SwiftUI 中动态计算字符串的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个名为:This
的文本.我想弄清楚名为 This
的文本的宽度,以便我可以为另一个视图的框架分配一个宽度.我该怎么做?
Let's say I have a text called: This
. I want to figure out the width of the text called This
so that I can assign a width to another view's frame. How do I go about it?
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#>)
}
}
推荐答案
这个对 String
的扩展应该建立在 Sweeper 的建议之上,让你获得一个 String
的宽度给定某种字体:
This extension to String
should build on Sweeper's suggestion to let you get the width of a String
given a certain font:
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))
这篇关于如何在 SwiftUI 中动态计算字符串的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文