[英]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:我在 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.在 iOS 14 中,它看起来像这样。 Well, I google it too, as it is also the 1st time for me to customize the background image of navigation bar.好吧,我也google了,因为这也是我第一次自定义导航栏的背景图片。 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.