导航栏中的中心图像

Centre image in navigation bar

我正在调用 JSQMessageViewController 并添加图像作为标题,但由于 Back left-button.

引起的偏移,它没有居中

这是我添加图片的代码:

let imageView = UIImageView()
    imageView.frame.size.width = 40
    imageView.frame.size.height = 40
    imageView.contentMode = .scaleAspectFit
    let image = UIImage(named: "avatar_example")
    imageView.image = image
    navigationItem.titleView = imageView

谢谢 :)

您需要实际获取 UINavigationBar 的宽度和高度,并相应地使图像居中。试试这个

    guard let bar = navigationController.navigationBar else { return }
    let bannerWidth = bar.frame.size.width
    let bannerHeight = bar.frame.size.height

    // centers image vertically & horizontally
    let bannerX = bannerWidth / 2 - imageView.frame.width / 2
    let bannerY = bannerHeight / 2 - imageView.frame.height / 2

    imageView.frame = CGRect(x: bannerX, y: bannerY, width: bannerWidth, height: bannerHeight)
    imageView.contentMode = .scaleAspectFit

    navigationItem.titleView = logoImageView

您确定问题出在 JSQMessageViewController 中吗?也许您只需要使用标题视图 (44*44) 中的标准尺寸进行对齐。

    let imageView = UIImageView(image: UIImage(named: "avatar_example"))
    imageView.contentMode = .scaleAspectFit
    let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
    imageView.frame = titleView.bounds
    titleView.addSubview(imageView)

    self.navigationItem.titleView = titleView