iOS 13 UISearchBar 获取UITextField

在iOS 13 之前都是通过

[self.searchBar valueForKey:@"_searchField"];

iOS 13 就直接废弃了 直接通过控件的私有属性获取控件方法

  • 所以可以通过这种形式获取
UITextField *searchField = (UITextField*)[self.searchBar findSubview:@"UITextField" resursion:YES];

searchField.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15];

searchField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 5, 0, 0)];

通过UIView的分类 遍历 查询 UITextField


- (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;
}

你可能感兴趣的:(iOS 13 UISearchBar 获取UITextField)