iOS 13 自定义 UISearchBar _searchField 崩溃

3

使用新的iOS 13系统时,我试图使用valueForKey:@"_searchField"更改UISearchBartextField属性时出现了崩溃。

现在似乎苹果公司已经改变了一些东西。

我创建了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编写相同的代码,可以将其添加到答案中。

愉快的编码!

3个回答

10

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

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

2
你可以通过使用以下的 扩展程序 来实现。最初的回答。
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
    }
}

"Use like:"翻译成中文是"使用方式:"。
self.searchBar.getAllSubview(type: UITextField.self).first

输出:

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

1

我的项目使用Objective c,我需要同时支持XCode10,所以,在头疼了两天后,以下代码解决了我的问题:

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

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

Swift 中也可以使用相同的方法。

希望对某些人有所帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接