制作一个足够大的 SwiftUI TextField 来容纳一个字符串
Make a SwiftUI TextField big enough to fit a string
我想使用 SwiftUI 制作一个足够宽以容纳一定数量数字的 TextField。它应该考虑到当前的字体,所以我不能使用固定值。
我知道我可以获得当前字体:()
@Environment(\.font) var font
然后将其转换为具有 table 的 UIFont:()
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:
...
并通过执行以下操作获取字符串的宽度:
()
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的原因,得到的框有点小,整个过程有点绕
有没有更简单的方法?
您可以创建一个 Text
尽可能长的字符串并将其隐藏。然后将实际的 TextField
放入 overlay
:
Text("9999999999")
.opacity(0)
.overlay(TextField("", text: $text))
我想使用 SwiftUI 制作一个足够宽以容纳一定数量数字的 TextField。它应该考虑到当前的字体,所以我不能使用固定值。
我知道我可以获得当前字体:()
@Environment(\.font) var font
然后将其转换为具有 table 的 UIFont:()
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:
...
并通过执行以下操作获取字符串的宽度:
(
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的原因,得到的框有点小,整个过程有点绕
有没有更简单的方法?
您可以创建一个 Text
尽可能长的字符串并将其隐藏。然后将实际的 TextField
放入 overlay
:
Text("9999999999")
.opacity(0)
.overlay(TextField("", text: $text))