ios UISearchBar 修改搜索框文字大小

2020-12-30  本文已影响0人  木子李55
搜索页面

一、问题描述
通过以下设置在ios13之前有效,在ios13之后会造成设置字体大小失效,

for (UIView *subView in [[searchBar.subviews lastObject] subviews]) {
            if ([[subView class] isSubclassOfClass:[UITextField class]]) {
                UITextField *textField = (UITextField *)subView;
                textField.font = [UIFont systemFontOfSize:14];
                _searchTextField = textField;
                break;
            }
 }
因为打印searchBar.subviews.lastObject.subviews在ios13之前:
<__NSArrayM 0x2818fc210>(
<UISearchBarBackground: 0x1064f6160; frame = (0 0; 0 0); userInteractionEnabled = NO; layer = <CALayer: 0x281617240>>,
<UISearchBarTextField: 0x10681e000; frame = (0 0; 0 0); text = ''; opaque = NO; layer = <CALayer: 0x2816145e0>>
)
在ios13之后:
<__NSArrayM 0x282d96940>(
<UISearchBarBackground: 0x1063c5500; frame = (0 0; 0 0); userInteractionEnabled = NO; layer = <CALayer: 0x282300f00>>,
<_UISearchBarSearchContainerView: 0x1063c5920; frame = (0 0; 0 0); autoresize = W; gestureRecognizers = <NSArray: 0x282d76d30>; layer = <CALayer: 0x282301400>>
)

所以if里面的设置不再执行。

二、解决方法

在ios13之后UISearchBar暴露了UITextField属性,这点算是苹果的优化,方便取了,但是你搞下兼容啊......

现在如下设置:
if (@available(iOS 13.0, *)) {
        UITextField *tf = searchBar.searchTextField;
        tf.font = [UIFont systemFontOfSize:14];
    } else {
        for (UIView *subView in [[searchBar.subviews lastObject] subviews]) {
            if ([[subView class] isSubclassOfClass:[UITextField class]]) {
                UITextField *textField = (UITextField *)subView;
                textField.font = [UIFont systemFontOfSize:14];
                _searchTextField = textField;
                break;
            }
        }
    }
上一篇下一篇

猜你喜欢

热点阅读