Search code examples
iosswiftiphoneautolayoutuikit

How to center vertically UIImage inside parent view programmatically using CGRect?


I tried to do this one but, the place of the Image changes when I try to run on a different iPhone model in Simulator. I need to do this exactly with CGRect. Thanks in Advance!

    func configure() {
        //MARK: Logo Image
        view.addSubview(logo)
        logo.image = UIImage(named: "cafelogo")
        logo.layer.cornerRadius = 25
        logo.frame = CGRect(x: 100, y: 200, width: 150, height: 150)

Solution

  • You should be using auto-layout constraints -- but first, to show you how to do this with explicit rect / framing:

    func configure() {
        //MARK: Logo Image
        view.addSubview(logo)
        logo.image = UIImage(named: "cafelogo")
        logo.layer.cornerRadius = 25
        logo.frame = CGRect(x: 0, y: 0, width: 150, height: 150)
        // center it in the view
        logo.center = view.center
    }
    

    but... you have to call this from viewDidLayoutSubviews(). Otherwise, view's frame has not yet been laid-out:

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        configure()
    }
    

    Note that if the frame of view changes - such as on device rotation - your logo image view will no longer be centered. You could add some new code to re-center it, but it is much easier to let auto-layout do all the work.

    You can use this code in viewDidLoad():

        logo.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(logo)
        logo.image = UIImage(named: "cafelogo")
        logo.layer.cornerRadius = 25
        NSLayoutConstraint.activate([
            logo.widthAnchor.constraint(equalToConstant: 150.0),
            logo.heightAnchor.constraint(equalToConstant: 150.0),
            logo.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            logo.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        ])
    

    Now your logo image view is 150x150 and will always remain centered in view.