Search code examples
iosswiftuiimageviewuinavigationitemtitleview

Swift3 iOS -Rounded ImageView in Navigation TitleView Keeps Showing Square?


I have a rounded imageView that I use for the profile pic in my app. I use the code several times throughout the app in tableView cells and on different views in view controllers. The profile pic always displays as round. When I use the below code to set the profile pic to round inside the navItem's titleView it only displays as a square.

Why doesn't it display round in the navItem's titleView?

var url: String?//it's already set with some value

override func viewDidLoad() {
        super.viewDidLoad(){

        setTitleView(urlStr: url)
{

func setTitleView(urlStr: String?){

        let titleView = UIView()
        titleView.frame = CGRect(x: 0, y: 0, width: 44, height: 44)

        let containerView = UIView()
        containerView.translatesAutoresizingMaskIntoConstraints = false
        titleView.addSubview(containerView)

        let imageView = UIImageView()
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.contentMode = .scaleAspectFill
        imageView.layer.cornerRadius = imageView.frame.size.width / 2
        imageView.clipsToBounds = true
        imageView.layer.borderColor = UIColor.white.cgColor
        imageView.layer.borderWidth = 0.5
        imageView.backgroundColor = UIColor.white

        if let urlStr = urlStr{
            let url = URL(string: urlStr)
            imageView.sd_setImage(with: url!)
        }

        containerView.addSubview(imageView)

        imageView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
        imageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
        imageView.widthAnchor.constraint(equalToConstant: 40).isActive = true
        imageView.heightAnchor.constraint(equalToConstant: 40).isActive = true

        containerView.centerXAnchor.constraint(equalTo: titleView.centerXAnchor).isActive = true
        containerView.centerYAnchor.constraint(equalTo: titleView.centerYAnchor).isActive = true

        navigationItem.titleView = titleView
}

Solution

  • Looks like imageView.layer.cornerRadius = imageView.frame.size.width / 2 is set to 0. imageView.frame.size.width is equal to 0 here.

    Instead of let imageView = UIImageView(), you can predefine the frame when creating the imageView with let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))