Ron Baker
Ron Baker

Reputation: 381

Center UIImageView inside UIView

So I have a UIImageView named currentEventImage that is inside an UIView blurryBackGround. I currently want to center the UIImageView in the UIView. Below is my current code

//Subviews will be added here
view.addSubview(blurryBackGround)
view.addSubview(currentEventImage)
view.addSubview(currentEventDate)

//Constraints will be added here
_ = blurryBackGround.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 17, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: self.view.frame.width, height: 330)
currentEventImage.heightAnchor.constraint(equalToConstant: 330).isActive = true
currentEventImage.topAnchor.constraint(equalTo: blurryBackGround.topAnchor, constant: 5).isActive = true
currentEventImage.center = blurryBackGround.center
blurryBackGround.addSubview(currentEventImage)

Any idea how I would do that?

currentEventImage.center = blurryBackGround.convert(blurryBackGround.center, from: blurryBackGround.superview)

Tried this and it didn't work

Upvotes: 3

Views: 3721

Answers (2)

Swati Gautam
Swati Gautam

Reputation: 191

You can use the following example code:-

Here I have given the width and height of View as (200,400) and for UIImageView I have given the size as (50,50)

let whitView = UIView(frame:CGRect(self.view.frame.size.width/2-200/2,self.view.frame.size.height/2-400/2,200,400))
whitView.backgroundcolor = UIColor.white
view.addSubview(whitView)
let imgView = UIImageView(frame:CGRect(whitView.frame.size.width/2-50/2,whitView.frame.size.height/2-50/2,50,50))
imgView.image = UIImage(named: "abc.png")
whitView.addSubview(imgView)

Upvotes: 0

mugx
mugx

Reputation: 10105

You may want to try the following solution based on centerXAnchor and centerYAnchor (feel free to remove constraints on width/height):

import UIKit

class ViewController: UIViewController {
    @IBOutlet var niceIcon:UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        niceIcon.translatesAutoresizingMaskIntoConstraints = false
        niceIcon.heightAnchor.constraint(equalToConstant: 100).isActive = true
        niceIcon.widthAnchor.constraint(equalToConstant: 100).isActive = true
        niceIcon.centerXAnchor.constraint(lessThanOrEqualTo: niceIcon.superview!.centerXAnchor).isActive = true
        niceIcon.centerYAnchor.constraint(lessThanOrEqualTo: niceIcon.superview!.centerYAnchor).isActive = true
    }
}
  1. example of storyboard, raw icon misplaced and without any constraints.

enter image description here

  1. on the simulator:

enter image description here


another solution (a bit more verbose) might be to add constraints, with the same constant, on leftAnchor, rightAnchor, bottomAnchor, topAnchor. Such constant stands for the distance between the superview and the subview itself.

Upvotes: 6

Related Questions