我的问题基本上已经在标题中说明了。我尝试为
然而,我的应用程序似乎没有很好地处理它,如下所示:
字体似乎随着此更新的代码进行了缩放,但搜索栏的高度并没有增加。
UISearchBar
添加动态类型(如此处定义),但没有成功。我知道这是可能的,因为系统应用程序似乎可以处理它,如此处所示:
![enter image description here](https://istack.dev59.com/osiNl.webp)
知道UITextField
包含在UISearchBar
中,我自然而然地尝试了这个解决方案,但没有成功:UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).adjustsFontForContentSizeCategory = true
我还尝试在网上搜索/查看文档,但似乎找不到解决方案。我是否缺少某些内容以使动态类型在UISearchBar
中起作用?
更新:
@matt建议我进行手动检查并以此方式更新字体。但是,这会产生另一个问题,因为搜索栏本身太小而无法容纳文本,如下所示:
@matt建议使用scaledValue(for:)
方法也更新高度,但似乎不起作用。以下是我正在使用的代码:
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).font = UIFont.preferredFont(forTextStyle: .body)
let textFieldFrame = UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).frame
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).frame = CGRect(x: textFieldFrame.minX, y: textFieldFrame.minY, width: textFieldFrame.width, height: UIFontMetrics.default.scaledValue(for: textFieldFrame.height))
}
字体似乎随着此更新的代码进行了缩放,但搜索栏的高度并没有增加。
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
searchBar.textField?.font = UIFont.preferredFont(forTextStyle: .body)
if let textFieldFrame = searchBar.textField?.frame {
searchBar.textField?.frame = CGRect(x: textFieldFrame.minX, y: textFieldFrame.minY, width: textFieldFrame.width, height: UIFontMetrics.default.scaledValue(for: textFieldFrame.height))
}
}
另外,这是我找到textField的方法(以防其他卡住的用户想知道):
extension UISearchBar {
var textField: UITextField? {
var _textField: UITextField? = nil
subviews.forEach {
$0.subviews.forEach {
if let textField = $0 as? UITextField {
_textField = textField
}
}
}
return _textField
}
}