Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the size of titleView in navigation bar. Because there's a gap between titleView and backButton in navigationBar

I've added a search bar to my navigation.titleView

    self.navigationItem.titleView = searchBar

There's also a BackBarButtonItem with title = ""

    self.navigationItem.backBarButtonItem?.title = ""

But then there're gap between Back Button and SearchBar, like this: There're gap between Back Button and SearchBar

I Think that the gap appears here because there's space for title of backBarButtonItem (because my title is null "" but the space still there)

So I want to ask how to omit that gap? I want to make my searchBar nearer my backBarIcon

Thank you so much!

EDIT 1: I try to change searchBar's frame but it's not working

This is my code

    //Change searchBar's frame        
    let titleViewFrame = (searchController.searchBar.frame)
    searchController.searchBar.frame = CGRect(x: titleViewFrame.minX - 20.0, y: titleViewFrame.minY, width: titleViewFrame.width + 20.0, height: titleViewFrame.height)
like image 442
Nguyễn Anh Việt Avatar asked Feb 24 '17 03:02

Nguyễn Anh Việt


2 Answers

override func viewDidLoad() {
    super.viewDidLoad()

    let container = UIView(frame: CGRect(x: 0, y: 0, width: 1000, height: 22))

    let searchBar = UISearchBar()
    searchBar.translatesAutoresizingMaskIntoConstraints = false
    container.addSubview(searchBar)

    let leftButtonWidth: CGFloat = 35 // left padding
    let rightButtonWidth: CGFloat = 75 // right padding
    let width = view.frame.width - leftButtonWidth - rightButtonWidth
    let offset = (rightButtonWidth - leftButtonWidth) / 2

    NSLayoutConstraint.activate([
        searchBar.topAnchor.constraint(equalTo: container.topAnchor),
        searchBar.bottomAnchor.constraint(equalTo: container.bottomAnchor),
        searchBar.centerXAnchor.constraint(equalTo: container.centerXAnchor, constant: -offset),
        searchBar.widthAnchor.constraint(equalToConstant: width)
    ])


    self.navigationItem.titleView = container
}

enter image description here

like image 90
Peter Cheng Avatar answered Nov 18 '22 22:11

Peter Cheng


You can't do that, there is a default space given which we cannot change if we have back button.

 self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
        self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: "back")

    self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "back")

    self.navigationController?.navigationBar.tintColor = UIColor.lightGray

Below is the screenshot enter image description here

like image 1
Arun Avatar answered Nov 18 '22 21:11

Arun