gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:04:03 28 4
gpt4 key购买 nike

假设我有一条短信:This .我想弄清楚名为 This 的文本的宽度这样我就可以为另一个 View 的框架分配一个宽度。我该怎么做?

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 的宽度给定某种字体 :

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))

关于ios - 如何在 SwiftUI 中动态计算字符串的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58782245/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com