首页 > 解决方案 > 无法将图像(个人资料图片)按钮添加到 UINavigationBar

问题描述

我试图让我UINavigationBar在左上角显示一个圆形的个人资料图片。我可以使用以下实例轻松地使其显示图像/图标。

self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: icon, style: .plain, target: self, action: #selector(funcToCall))

问题在于,当尝试使用个人资料图片时,自定义视图和图像实例都不会产生所需的结果。

尝试 1 -- Swift 4(图像实例化)

let img = originalImage.withRenderingMode(.alwaysOriginal)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: img, style: .plain, target: self, action: #selector(goToProfile))

此尝试产生 以下结果

问题:

尝试 2——Swift 4(自定义视图)

let idealButton = UIButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
idealButton.setImage(imgToUse, for: .normal)
idealButton.imageView?.contentMode = .scaleAspectFill

idealButton.imageView?.layer.cornerRadius = 0.5 * idealButton.frame.width
idealButton.imageView?.layer.borderWidth = 0.75
idealButton.imageView?.layer.borderColor = rgba(240,240,240,1).cgColor

idealButton.addTarget(self, action: #selector(goToProfile), for: .touchUpInside)
navigationItem.setLeftBarButton(UIBarButtonItem(customView: idealButton), animated: false)

此尝试产生以下结果

问题

任何帮助深表感谢。谢谢!

标签: iosswiftuinavigationbarimagebutton

解决方案


让我们尝试UIButton添加为子视图UINavigationBar

所以从创建按钮和设置它的属性开始(你可以lazy在全局范围内使用变量)

lazy var idealButton: UIButton = {
    let button = UIButton()
    button.setImage(imgToUse, for: .normal)
    button.imageView?.layer.cornerRadius = 16
    ... // set other button's properties (border, target, colors, etc.)
    return button
}()

现在将此按钮添加为 currentnavigationController的子视图navigationBar

guard let navigationBar = navigationController?.navigationBar else { return }
navigationBar.addSubview(idealButton)

然后只需为您的按钮设置约束(您需要根据需要设置高度和宽度,并且左侧和底部约束等于navigationBar的约束)

idealButton.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([
    idealButton.leftAnchor.constraint(equalTo: navigationBar.leftAnchor, constant: 20),
    idealButton.bottomAnchor.constraint(equalTo: navigationBar.bottomAnchor, constant: -6),
    idealButton.heightAnchor.constraint(equalToConstant: 32),
    idealButton.widthAnchor.constraint(equalToConstant: 32)
])

推荐阅读