iOS 11 中的导航栏自定义图像视图问题

Navigation bar custom image view issue in iOS 11

我将普通图像视图设置为我的导航栏项目的自定义视图,但实际情况是这样的:

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 34, height: 34))
imageView.kf.setImage(with: user.profilePictureURL)
if user.profilePictureURL == nil {
    imageView.image = #imageLiteral(resourceName: "ProfilePlaceholderSuit")
}
imageView.backgroundColor = .white
imageView.layer.masksToBounds = true
imageView.layer.cornerRadius = 17
imageView.layer.borderWidth = 1
imageView.layer.borderColor = UIColor.white.cgColor
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: imageView)
print("ok, so the image view frame is", imageView.frame) // 0, 0, 34, 34

这是 Kingfisher 框架的问题。我已经切换到 SDWebImage,它工作正常(有时)。

编辑:

这有效

let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.heightAnchor.constraint(equalToConstant: 34).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 34).isActive = true

由于在 iOS 11 UIBarButtonItem 中使用自动布局而不是框架,因此许多开发人员面临此类问题。

所以你只想在右上角的 barButton 项上设置个人资料图片,然后

否则,您可以在代码中添加 imageView 的约束,如下所示

    let widthConstraint = imageView.widthAnchor.constraint(equalToConstant: 34)
    let heightConstraint = imageView.heightAnchor.constraint(equalToConstant: 34)
    heightConstraint.isActive = true
    widthConstraint.isActive = true