Reputation: 21
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
I have tried using an image with the icon and text together so I could create one imageView
and set the titleView to that, however that results in a small centered view that overlays the large Navigation Bar.
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
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:
Upvotes: 1