无法将图像(个人资料图片)按钮添加到UINavigationBar

时间:2018-12-23 20:24:54

标签: ios swift uinavigationbar imagebutton

我正试图让我的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))

此尝试会产生 following result

问题:

  • 即使我指定了leftBarButtonItem,它也显示在中间
  • 由于无法更改cornerRadius,因此无法使用此策略制作圆形按钮。

尝试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)

此尝试将产生following result

问题

  • 图像跨越整个 UINavigationBar。它不受限于指定的尺寸。

非常感谢您的帮助。谢谢!

1 个答案:

答案 0 :(得分:2)

让我们尝试添加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
}()

现在将此按钮添加为当前navigationController的{​​{1}}的子视图

navigationBar

然后只需为按钮设置约束(您需要根据需要设置高度和宽度,左约束和底约束等于guard let navigationBar = navigationController?.navigationBar else { return } navigationBar.addSubview(idealButton) 的约束)

navigationBar