如何在旋转设备时为UISearchController制作autoLayout?

时间:2022-06-19 20:46:57

I'm using a UISearchController integrate with my tableview. For making my searchBar not scrolling with the table, I already made a View (name SearchBarView) under the navigation bar and my table is under this view. All element on my view is setting up using auto layout: 如何在旋转设备时为UISearchController制作autoLayout?

我正在使用UISearchController与我的tableview集成。为了使我的searchBar不滚动表,我已经在导航栏下创建了一个View(名称为SearchBarView),我的表位于此视图下。我视图中的所有元素都是使用自动布局设置的:

In my code. I make a UISearchController like a subview of SearchBarView and using sideToFit function for auto fit the width of the screen like this:

在我的代码中。我创建一个像SearchBarView子视图的UISearchController,并使用sideToFit函数自动调整屏幕的宽度,如下所示:

      self.resultSeachController = ({
            let controller = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self
            controller.dimsBackgroundDuringPresentation = false
            controller.searchBar.sizeToFit()

//            add searchbar in the searchbarView
            self.searchBarView.addSubview(controller.searchBar)
            return controller
        })()

My SearchBar is working perfect now except one: when I rotate the simulator, the searchBar is not automatic fit the width of screen. It only fit the screen when I touch the SearchBar for searching something. 如何在旋转设备时为UISearchController制作autoLayout?如何在旋转设备时为UISearchController制作autoLayout?如何在旋转设备时为UISearchController制作autoLayout?如何在旋转设备时为UISearchController制作autoLayout?

我的SearchBar现在工作正常,除了一个:当我旋转模拟器时,searchBar不能自动适应屏幕的宽度。当我触摸SearchBar进行搜索时,它只适合屏幕。

I don't know how to fix. I tried this code :

我不知道如何解决。我试过这段代码:

    override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {

        self.resultSeachController.searchBar.sizeToFit()

    }

But It's still not working. How can I fix that?

但它仍然无法正常工作。我该如何解决这个问题?

1 个解决方案

#1


4  

Do it while animating along with the transition:

在动画过程中同时执行此操作:

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator
{
    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        [_searchController.searchBar sizeToFit];
    } completion:nil];
}

#1


4  

Do it while animating along with the transition:

在动画过程中同时执行此操作:

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator
{
    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        [_searchController.searchBar sizeToFit];
    } completion:nil];
}