简体   繁体   中英

How to add image and button design to the navigation bar?

I want to add button and image to the design of the navigation bar but couldn't add the picture successfully. I tried the following code inside viewDidLoad:

 let logo = UIImage(named: "logo.png")
    let imageView = UIImageView(image:logo)
    navigationController?.navigationBar.barTintColor = UIColor.green
    self.navigationItem.titleView = imageView

I tried the code and the navigation bar looks like this: 在此处输入图像描述 As a result of the code I tried, there is space on the edges. I want to align the picture to the right of the screen. I want to align the button to the left of the screen.

The image of the design I want is as follows: 在此处输入图像描述

What code should I try for this?

You should try this, hope this will worked

let backButton: UIBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(back))
        self.navigationItem.leftBarButtonItem = backButton
    
    let logo = UIImage(named: "google_logo.png")
    let imageView = UIImageView(image:logo)
    imageView.contentMode = .scaleAspectFit
    self.navigationItem.titleView = imageView

在此处输入图像描述

Is this what you want? Though the background image is stretched as I just randomly pick an image, which doesn't has the correct resolution for navigation bar.

In iOS 14, it looks like this. Well, I google it too, as it is also the 1st time for me to customize the background image of navigation bar. I usually use a solid color for the background.

在此处输入图像描述

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        let img = UIImage(named: "Human")!
        navigationController?.navigationBar.setBackgroundImage(img.resizableImage(withCapInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0 ,right: 0), resizingMode: .stretch), for: .default)

        let backImg = UIImage(named: "back")?.withRenderingMode(.alwaysOriginal)
        let leftButton = UIBarButtonItem(image: backImg, style: .plain, target: self, action: #selector(backTapped))
        navigationItem.leftBarButtonItem = leftButton
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM