iosswiftuiviewsubviewtitleview

Swift Add UIView with subviews to titleView


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


Solution

  • 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.