简体   繁体   中英

Swift - Rounded UIImageView with constraints

I have a simple view controller and I want to put a rounded image view in it. (I don't use the storyboard at all, I want to everything programmatically) However, whatever I do, the image view is square.

class DetailViewController: UIViewController{

    // MARK: - Controls
    var imageView:UIImageView!;
    var label:UILabel = UILabel();
    var button:UIButton = UIButton();
    var close:UIButton = UIButton();

    // MARK: - Fields
    var person: Person!;

    // MARK: - Constructors
    init(person: Person) {
        super.init(nibName: nil, bundle: nil);

        self.person = person;
        self.view.backgroundColor = UIColor.whiteColor();
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

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

        self.imageView = UIImageView();
        self.imageView.image = person.picture;
        self.imageView.translatesAutoresizingMaskIntoConstraints = false;
        self.imageView.contentMode = .ScaleAspectFill;
        self.view.addSubview(self.imageView);

        self.label.translatesAutoresizingMaskIntoConstraints = false;
        self.label.text = person.name;
        self.label.sizeToFit();
        self.view.addSubview(self.label);

        self.button.setTitle("Open Webview", forState: .Normal);
        self.button.setTitleColor(UIColor.whiteColor(), forState: .Normal);
        self.button.backgroundColor = UIColor.grayColor();
        self.button.translatesAutoresizingMaskIntoConstraints = false;
        self.button.addTarget(self, action: #selector(DetailViewController.open), forControlEvents: .TouchUpInside);
        self.view.addSubview(self.button);

        self.close.setTitle("Close", forState: .Normal);
        self.close.setTitleColor(UIColor.blueColor(), forState: .Normal);
        self.close.backgroundColor = UIColor.clearColor();
        self.close.translatesAutoresizingMaskIntoConstraints = false;
        self.close.addTarget(self, action: #selector(DetailViewController.closeView), forControlEvents: .TouchUpInside);
        self.view.addSubview(self.close);
        self.close.alpha = 0;
        if( UIDevice.currentDevice().userInterfaceIdiom == .Pad) {
            self.close.alpha = 1;
        }

        // Center constraint
        self.view.addConstraint(NSLayoutConstraint(item: button, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0));
        self.view.addConstraint(NSLayoutConstraint(item: label, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0));
        self.view.addConstraint(NSLayoutConstraint(item: imageView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0));

        // position order constraint
        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[close(40)]-60-[imageView(150)]-20-[nameLabel(40)]-35-[button(40)]", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["close" : close,"imageView" : imageView, "nameLabel" : label, "button" : button]));

        //width constaints
        self.view.addConstraint(NSLayoutConstraint(item: button, attribute: .Width, relatedBy: .Equal, toItem: self.view, attribute: .Width, multiplier: 0.5, constant: 0));
        self.view.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: imageView, attribute: .Height, multiplier: 1, constant: 0));
        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[close(60)]-20-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["close" : close]));
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(false);
        let dSize: CGFloat = min(imageView.frame.height, imageView.frame.width)
        imageView.bounds = CGRectMake(0, 0, dSize, dSize) // centered in container you want to use bounds over frame for this scenario
        imageView.layer.cornerRadius = dSize/2.0
        imageView.layer.masksToBounds = true;
        imageView.layer.borderWidth = 3.0
        imageView.layer.borderColor = UIColor.redColor().CGColor
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func open() {

        if( UIDevice.currentDevice().userInterfaceIdiom == .Pad) {
            self.presentViewController(WebViewController(url: self.person.url), animated: false, completion: nil);
        } else {
            self.presentViewController(WebViewController(url: self.person.url), animated: true, completion: nil);
        }
    }

    func closeView() {
        self.dismissViewControllerAnimated(true, completion: nil);
    }

}

It works very well if I use frame instead of constraints but I want to do it with constraints as I am learning this.

Can someone give me directions please ?

Thanks in advance!

Put

    let dSize: CGFloat = min(imageView.frame.height, imageView.frame.width)
    imageView.bounds = CGRectMake(0, 0, dSize, dSize) // centered in container you want to use bounds over frame for this scenario
    imageView.layer.cornerRadius = dSize/2.0` 

in viewWillLayoutSubviews

Swift 4+

Create helper method in UIImageView extension with borderWidth and borderColor parameters having default values

import UIKit

extension UIImageView {

    func setRounded(borderWidth: CGFloat = 0.0, borderColor: UIColor = UIColor.clear) {
        layer.cornerRadius = frame.height / 2
        layer.masksToBounds = true
        layer.borderWidth = borderWidth
        layer.borderColor = borderColor.cgColor
    }
}

Example Usage

a) Simple Rounded UIImageView (without border)

override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()

        self.imageView.setRounded()
    }

b) Rounded UIImageView with Border Width and Color

override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()

        self.imageView.setRounded(borderWidth: 1.0, borderColor: UIColor.blue)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM