新视图但仍具有相同的NavigationBar

时间:2017-11-21 20:07:34

标签: ios swift uisearchbar navigationbar

我有NavigationBar UISearchBar。当我按下searchBar时,我想要显示一个新视图,但仍保持我的搜索栏处于活动状态(相同的navBar)。因为如果我只是使用pushViewController,新的视图会显示新的NavigationBar,而我的UISearchBar会消失。这是我的代码:

UISearchBar

extension HomeController {

func setupNavigationBar() {

    searchBar.delegate = self
    searchBar.searchBarStyle = UISearchBarStyle.minimal
    searchBar.placeholder = "Search"
    searchBar.barTintColor = UIColor.gray
    navigationItem.titleView = searchBar

}

public func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    searchBar.showsCancelButton = true
    let layout = UICollectionViewFlowLayout()
    let firstVC = HomeController(collectionViewLayout: layout)
    let secondVC = UserSearchController(collectionViewLayout: layout)


    self.addChildViewController(secondVC)
    secondVC.view.frame = firstVC.view.bounds;
    self.view.addSubview(secondVC.view)
    secondVC.didMove(toParentViewController: self)

    secondVC.view.frame = CGRect(x: firstVC.view.frame.size.width, y: secondVC.view.frame.origin.y, width: secondVC.view.frame.width, height: secondVC.view.frame.size.height)
    UIView.animate(withDuration: 0.33) {
        secondVC.view.frame = firstVC.view.bounds;
    }

}



}

public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searchBar.text = nil
    searchBar.endEditing(true)
    searchBar.showsCancelButton = false


}


func hideSearchBar() {
    navigationItem.setRightBarButton(searchBarButtonItem, animated: true)
    label.alpha = 0
    UIView.animate(withDuration: 0.3, animations: {
        self.navigationItem.titleView = self.label
        self.label.alpha = 1
        }, completion: { finished in

        })
    }

}

新观点:

import UIKit


class UserSearchController: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = UIColor.blue


    }

}

1 个答案:

答案 0 :(得分:0)

实际上导航栏不会改变,它仍然是同一个对象。但是当顶视图控制器发生变化时,导航控制器会使用新视图控制器的导航项信息更新导航栏内容。

所以,你可以做两件事; 1-您可以直接将搜索栏添加为导航栏的子视图,而不是通过导航项。所以导航控制器不会改变任何关于栏的内容。但我个人并不建议这样做,因为你需要自己处理搜索栏的可见性。

2-而不是推动第二个视图控制器,您可以将其作为子视图控制器添加到第一个视图控制器,并将其动画到屏幕中。由于导航控制器的顶视图控制器不会更改,导航栏内容保持不变。

第二个选项的代码示例;

// Add the second view controller as a child of the first view controller
[firstVC addChildViewController:secondVC];
secondVC.view.frame = firstVC.view.bounds;
[firstVC.view addSubview:secondVC.view];
[secondVC didMoveToParentViewController:firstVC];

// Now you can animate it as if it's pushed to the navigation controller, or anyway else you want
secondVC.view.frame = CGRectMake(firstVC.view.frame.size.width, secondVC.view.frame.origin.y, secondVC.view.frame.size.width, secondVC.view.frame.size.height);
[UIView animateWithDuration:0.33 animations:^{
    secondVC.view.frame = firstVC.view.bounds;
}];