iOS 13自定义UISearchBar _searchField崩溃

时间:2019-06-19 09:26:51

标签: ios objective-c uitextfield uisearchbar ios13

在新的iOS 13上,尝试使用valueForKey:@"_searchField"更改UISearchBar textField属性时崩溃了

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

我已经使用以下自定义方法创建了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片段,如果有人知道如何快速编写相同的代码,则可以将其添加到答案中。

编码愉快!

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您可以使用下面的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>>

答案 2 :(得分:0)

我的项目位于 Objective c 中,我也需要支持 XCode10 ,因此,在经过两天的头痛之后,我的工作得以保存:

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

只需从旧代码中删除 _

Swift 中,您也可以使用它。

希望它将对某人有所帮助!