【发布时间】:2020-11-12 05:47:31
【问题描述】:
我想使用 SwiftUI 制作一个足够宽的 TextField 以容纳一定数量的数字。它应该考虑到当前字体,所以我不能使用固定值。
我知道我可以通过以下方式获取当前字体:(https://stackoverflow.com/a/62156787/1115020)
@Environment(\.font) var font
并将其转换为带有表格的 UIFont:(https://stackoverflow.com/a/64491669/1115020)
extension UIFont {
class func with(font: Font) -> UIFont {
let uiFont: UIFont
switch font {
case .largeTitle:
uiFont = UIFont.preferredFont(forTextStyle: .largeTitle)
case .title:
uiFont = UIFont.preferredFont(forTextStyle: .title1)
case .title2:
...
并通过执行以下操作获取字符串的宽度: (https://stackoverflow.com/a/58782429/1115020)
extension String {
func widthOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttributes)
return size.width
}
}
最后适当地设置框架:
.frame(width: "9999".widthOfString(usingFont: UIFont.with(font: font ?? .body)))
但是生成的盒子因为有padding的原因有点太小了,整个过程有点复杂。
有没有更简单的方法?
【问题讨论】: