2

I'd like to customize my navigation bar and insert a UIView with two subviews into the title view of the navigation bar. Unfortunately the subviews aren't displayed. Do you have any idea why?

    let titleContainer = UIView()
    titleContainer.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)

    let searchIcon = UIButton()
    searchIcon.setImage(UIImage(named: "search_icon"), for: UIControlState.normal)
    searchIcon.layer.frame = CGRect(x: 0, y: (UIScreen.main.bounds.size.height - 28) / 2, width: 28, height: 28)
    titleContainer.addSubview(searchIcon)

    let titleLabel = UILabel()
    titleLabel.frame = CGRect(x: 28, y: UIScreen.main.bounds.size.height, width: UIScreen.main.bounds.size.width-28, height: UIScreen.main.bounds.size.height)
    titleLabel.textColor = UIColor(red:255, green:255, blue:255, alpha:1.0)
    titleContainer.addSubview(self.titleLabel)

    self.navigationItem.titleView = titleContainer

problem and expected solution:

enter image description here

Arnab
  • 4,216
  • 2
  • 28
  • 50
N. Beer
  • 109
  • 1
  • 10
  • Your all the frames are UIScreeen Main screen that big . as you are using `UIScreen.main.bounds` provide valid frames then it should display – Prashant Tukadiya Apr 12 '18 at 11:51

2 Answers2

0

Have you considered making your let bar = UINavigationBar() programmatically and then add it with: self.view.addSubview(bar)?

So you can push all the "UIBarItems" you want..?

Sam
  • 819
  • 2
  • 7
  • 17
  • I also have it in my storyboard, that's why I haven't programmed the Navbar. The thing is, if I add the titleLabel or searchIcon by itself it is displayed. But if I add the container with the subviews nothing shows up. – N. Beer Apr 12 '18 at 11:40
0

Why did you use height of all the element as UIScreen.main.bounds.size.height? Please try the below code.

P.S. I have changed the color of searchIcon as i didn't have the image and changed the color of text of label and added some text so that it is visible.

    let titleContainer = UIView()
    titleContainer.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 45)

    let searchIcon = UIButton()
    //searchIcon.setImage(UIImage(named: "search_icon"), for: UIControlState.normal)
    searchIcon.backgroundColor = UIColor.red
    searchIcon.layer.frame = CGRect(x: 0, y: 8, width: 28, height: 28)
    titleContainer.addSubview(searchIcon)

    let titleLabel = UILabel()
    titleLabel.frame = CGRect(x: 28, y: 8, width: UIScreen.main.bounds.size.width-28, height: 30)
    titleLabel.textColor = UIColor.blue//(red:255, green:255, blue:255, alpha:1.0)
    titleContainer.addSubview(titleLabel)
    titleLabel.text = "Sample Text"

    self.navigationItem.titleView = titleContainer

Here is the screenshot of the above code:

enter image description here

Please change the x,y accordingly as per your requirement.

Arnab
  • 4,216
  • 2
  • 28
  • 50