I am trying to place an image logo as a title within the navigation bar of an iOS app using Swift. I included the image in the assets folder (Images.xcassets). I looked into this question but no luck.
The following is my code:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let logo = UIImage(named: "logo") as UIImage
let imageView = UIImageView(image:logo)
imageView.frame.size.width = 200;
imageView.frame.size.height = 45;
self.navigationItem.titleView = imageView
}
...
}
Change the Bar StyleA user changes the navigation bar's style, or UIBarStyle , by tapping the “Style” button to the left of the main page. This button opens an action sheet where users can change the background's appearance to default, black-opaque, or black- translucent.
I managed to create a Swift solution. Not sure if its the best way, but it works. I basically translated nerowolfe's code, and used the addSubview function.
class NavigationBar: UINavigationBar {
init(frame: CGRect) {
super.init(frame: frame)
initialise()
}
init(coder aDecoder: NSCoder!){
super.init(coder: aDecoder)
initialise()
}
func initialise(){
let logo = UIImage(named: "logo");
let imageView = UIImageView(image:logo)
imageView.frame.size.width = 145;
imageView.frame.size.height = 33;
imageView.frame.origin = CGPoint(x: 2, y: 8)
addSubview(imageView)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With