UISearchBar increases navigation bar height in iOS 11

后端 未结 19 1583
醉酒成梦
醉酒成梦 2020-11-28 02:47

I have my UISearchBar being part of the navigation bar like:

 let searchBar = UISearchBar()
 //some more configuration to the search bar
 .....
         


        
19条回答
  •  甜味超标
    2020-11-28 03:07

    I found Mai Mai's solution to be the only one that's really usable.
    However it's still not perfect:
    When rotating the device, the search bar is not properly resized and remains in the smaller dimension.

    I have found a fix for that. Here is my code in Objective C with the relevant parts annotated:

    // improvements in the search bar wrapper
    @interface SearchBarWrapper : UIView
    @property (nonatomic, strong) UISearchBar *searchBar;
    - (instancetype)initWithSearchBar:(UISearchBar *)searchBar;
    @end
    @implementation SearchBarWrapper
    - (instancetype)initWithSearchBar:(UISearchBar *)searchBar {
        // setting width to a large value fixes stretch-on-rotation
        self = [super initWithFrame:CGRectMake(0, 0, 4000, 44)];
        if (self) {
            self.searchBar = searchBar;
            [self addSubview:searchBar];
        }
        return self;
    }
    - (void)layoutSubviews {
        [super layoutSubviews];
        self.searchBar.frame = self.bounds;
    }
    // fixes width some cases of resizing while search is active
    - (CGSize)sizeThatFits:(CGSize)size {
        return size;
    }
    @end
    
    // then use it in your VC
    @implementation MyViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.navigationItem.titleView = [[SearchBarWrapper alloc] initWithSearchBar:self.searchController.searchBar];
    }
    @end
    

    Now there is still one case left that I haven't figured out yet. To reproduce do the following:
    - start in portrait
    - activate search field
    - rotate to landscape
    - error: the bar doesn't resize

提交回复
热议问题