UItextField within UISearchbar failing after iOS 7 upgrade

前端 未结 4 828
无人及你
无人及你 2020-12-18 16:11

I have a UITextField for the UISearchBar which this was working until iOS 7 upgrade and now it fails at this line: UITextField *textfield=(UITextField*)[[searchBar sub

4条回答
  •  一向
    一向 (楼主)
    2020-12-18 17:04

    It's not a good idea to assume that second searchBar's subview will be UITextField.

    I printed out subviews for UISearchBar, that's what I got on iOS 7:

    <__NSArrayM 0x17d141f0>(
    >
    )
    

    Only one subview, so your ... objectAtIndex:1] will definitely crash.

    You can use the following category for UIView to find UITextField in your searchBar:

    @interface UIView(Utils)
    
    -(UIView*)findSubviewRecursivelyOfClass:(Class)subviewClass;
    
    @end
    
    @implementation UIView(Utils)
    
    -(UIView*)findSubviewRecursivelyOfClass:(Class)subviewClass
    {
      if( [self isKindOfClass:subviewClass] ) {
        return self;
      } else {
        for( UIView* child in self.subviews ) {
          UIView* result = [child findSubviewRecursivelyOfClass:subviewClass];
          if( result ) {
            return result;
          }
        }
        return nil;
      }
    }
    
    @end
    

提交回复
热议问题