3

I'm setting a normal image view as a custom view for my nav bar item but this is what it's happening:

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

enter image description here

iPatel
  • 46,010
  • 16
  • 115
  • 137
Cesare
  • 9,139
  • 16
  • 78
  • 130

2 Answers2

3

This types of issue faced by many developers because of in iOS 11 UIBarButtonItem uses auto-layout instead of frames.

So you just want to set profile image on top right barButton items then please check my answer..

Other wise you can add constraints of imageView in you code like below

    let widthConstraint = imageView.widthAnchor.constraint(equalToConstant: 34)
    let heightConstraint = imageView.heightAnchor.constraint(equalToConstant: 34)
    heightConstraint.isActive = true
    widthConstraint.isActive = true
iPatel
  • 46,010
  • 16
  • 115
  • 137
0

This was a problem with the Kingfisher framework. I've switched to SDWebImage and it works fine (sometimes).

Edit:

This worked

let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.heightAnchor.constraint(equalToConstant: 34).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 34).isActive = true
Cesare
  • 9,139
  • 16
  • 78
  • 130
  • 1
    No it's not problem with the Kingfisher framework, it's issue of iOS 11 your should use autolayout instead of frame – iPatel Oct 06 '17 at 11:08
  • Thanks @iPatel. Do I have to constraint the image view to the navigation bar or just set its height and width? – Cesare Oct 06 '17 at 11:09
  • That works @iPatel. feel free to post that as an answer – Cesare Oct 06 '17 at 11:13
  • But why you using image view and add UITapGestureRecognizer even UIButton provide inbuilt functionality? – iPatel Oct 06 '17 at 11:20
  • So I could set the image of the image view easily with Kingfisher, but yeah good point. – Cesare Oct 06 '17 at 11:22
  • By SDWebImage you can also set image of UIButton and you can also follow this way https://stackoverflow.com/questions/44442573/navigation-bar-rightbaritem-image-button-bug-ios-11/46603200#46603200 – iPatel Oct 06 '17 at 11:24