Emre Cakir
Emre Cakir

Reputation: 21

Use imageView as title for Navigation Bar with preferLargeTitles

I would like to use a custom icon with text as the title for a Navigation Bar with preferLargeTitles enabled. The custom title needs to be large and left centered at first then resize when scrolling. This is what it should look like: Large Navigation Bar w/ Title that contains icon and text

enter image description here

I have tried using an image with the icon and text together so I could create one imageViewand set the titleView to that, however that results in a small centered view that overlays the large Navigation Bar.

enter image description here

How should I go about doing this? I want the custom title to behave just like the default large navigation bar and resize and center the image when scrolling up. Thanks!

Upvotes: 2

Views: 383

Answers (1)

Arnab
Arnab

Reputation: 4356

Try this

    // Create a navView to add to the navigation bar
    let navView = UIView()

    // Create the label
    let label = UILabel()
    label.text = "Assignment"
    label.font = UIFont.systemFont(ofSize: 30.0, weight: .bold)
    label.sizeToFit()
    label.center = navView.center
    label.textAlignment = NSTextAlignment.center

    // Create the image view
    let image = UIImageView()
    image.image = UIImage(named: "logo.png")
    let imageAspect = image.image!.size.width/image.image!.size.height
    image.frame = CGRect(x: label.frame.origin.x-label.frame.size.height*imageAspect - 5, y: label.frame.origin.y, width: label.frame.size.height*imageAspect, height: label.frame.size.height)
    image.contentMode = UIViewContentMode.scaleAspectFit

    // Add both the label and image view to the navView
    navView.addSubview(label)
    navView.addSubview(image)

    // Set the navigation bar's navigation item's titleView to the navView
    self.navigationItem.titleView = navView
    self.navigationController?.navigationBar.prefersLargeTitles = true

Output:

enter image description here

Upvotes: 1

Related Questions