iOS 13 自定义 UISearchBar _searchField崩溃



在新的iOS 13中,我在尝试使用valueForKey:@"_searchField"更改UISearchBar文本字段属性时遇到崩溃

现在看来,苹果已经改变了一些东西。

我已经使用以下自定义方法创建了 UIView 的子类,现在它似乎可以工作了!

- (UIView *)findSubview:(NSString *)name resursion:(BOOL)resursion
{
    Class class = NSClassFromString(name);
    for (UIView *subview in self.subviews) {
        if ([subview isKindOfClass:class]) {
            return subview;
        }
    }
    if (resursion) {
        for (UIView *subview in self.subviews) {
            UIView *tempView = [subview findSubview:name resursion:resursion];
            if (tempView) {
                return tempView;
            }
        }
    }
    return nil;
} 

您可以简单地以这种方式调用此方法来更改 UITextField 属性:

UITextField *textField = (UITextField*)[self findSubview:@"UITextField" resursion:YES];

显然,这是一个 Objective-c 片段,如果有人知道如何用 swift 编写相同的代码,可以将其添加到答案中。

祝您编码愉快!

我不确定它是否有帮助,但是UISearchBar有一个新的searchTextField属性,允许您访问其UISearchTextField,进而访问其UITextField:

let searchBar = UISearchBar()
var searchField : UITextField
if #available(iOS 13.0, *) {
    searchField = searchBar.searchTextField
} else {
    searchField = //Your original method
}
您可以使用

以下extension

extension UISearchBar {
    func getAllSubview<T : UIView>(type : T.Type) -> [T]{
        var all = [T]()
        func getSubview(view: UIView) {
            if let aView = view as? T{
                all.append(aView)
            }
            guard view.subviews.count>0 else { return }
            view.subviews.forEach{ getSubview(view: $0) }
        }
        getSubview(view: self)
        return all
    }
}

像这样使用:

self.searchBar.getAllSubview(type: UITextField.self).first

输出:

<UISearchBarTextField: 0x7fc68d850a00; frame = (0 0; 0 0); text = ''; opaque = NO; layer = <CALayer: 0x600000d29aa0>>

我的项目在目标 c 中,我也需要支持 XCode10,经过两天的头痛,下面行拯救了我的一天:

txfSearchField = [_searchBar valueForKey:@"searchField"];

只需要从旧代码中删除 _!!

Swift 中,你也可以使用相同的。

希望它能帮助某人!

最新更新