skip to Main Content

I want to display title of my each view in tabview at the top with the text being left aligned, currently when I toggle the top titlebar in storyboard I get something like this:

storyboard view titlebar

But when I run my app the title isn’t displayed like this, how do I show this when the app is running??

Update 1:

I am able to show the title bar by embedding the tabview controller inside a navigationview controller. Now the only issue I have is setting the alignment of the title to left.

2

Answers


  1. Chosen as BEST ANSWER

    I wrote a custom extension to UINavigationItem that sets the title left aligned:

    extension UINavigationItem {
        
        // MARK: Use this Method for setting up title for Any Controller *ALWAYS*
        public func setTitle(_ title: String, leftInset: CGFloat = -5) {
            let label = UILabel()
            label.text = title
            label.textAlignment = .left
            let customView = UIView()
            customView.translatesAutoresizingMaskIntoConstraints = false
            label.translatesAutoresizingMaskIntoConstraints = false
            customView.backgroundColor = .clear
            label.textAlignment = .left
            customView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 0)
    
            if #available(iOS 12, *) {
                label.frame.origin = CGPoint(x: leftInset + 3, y: -13)
            } else {
                label.frame.origin = CGPoint(x: leftInset, y: -13)
            }
            customView.addSubview(label)
            customView.layoutIfNeeded()
            customView.sizeToFit()
            label.layoutIfNeeded()
            label.sizeToFit()
            customView.translatesAutoresizingMaskIntoConstraints = true
            label.translatesAutoresizingMaskIntoConstraints = true
            titleView = customView
        }
    }
    

    Add this in each UIViewController that is used in the tabview:

    override func viewWillAppear(_ animated: Bool) {
            tabBarController?.navigationItem.setTitle("Sample", leftInset: 12)
        }
    

    The tabviewcontroller has to be embedded inside navigationviewcontroller for this to work.


  2. Try this:

    navigationItem.largeTitleDisplayMode = .always
    navigationController?.navigationBar.prefersLargeTitles = true
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search