AlvinfromDiaspar
AlvinfromDiaspar

Reputation: 6814

iOS contraints to center an image is not working

I added 2 constraints to center an UIImageView within a UIView. The constraints are to center it vertically and horizontally. But for some reason it is not centering.

Note that the container UIView has constraints of margins for the top, bottom, left, right.

Why the centering is not working? Is it possible that the UIImageView itself needs an explicit size?

Unfortunately this is all done via Storyboard, so I have no snippets to share.

Upvotes: 3

Views: 5220

Answers (2)

keshav vishwkarma
keshav vishwkarma

Reputation: 1852

you can try below code, It is working fine.

override func viewDidLoad() {
    super.viewDidLoad()

    let myImageView = UIImageView()
    myImageView.backgroundColor = UIColor.redColor()
    self.view.addSubview(myImageView)
    myImageView.translatesAutoresizingMaskIntoConstraints = false
    // set contentMode to center image
    myImageView.contentMode = .Center

    // if you want some specific heigh and width of myImageView then uncomment below Two line to add the height & Width constraints.
    // view.addConstraint(NSLayoutConstraint(item: myImageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 200))
    // view.addConstraint(NSLayoutConstraint(item: myImageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 200))

    // if you do not set the height and width constrints then myImageView size depends on actual size of image.
    view.addConstraint(NSLayoutConstraint(item: myImageView, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0))
    view.addConstraint(NSLayoutConstraint(item: myImageView, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0))
}

Upvotes: 3

Badal Shah
Badal Shah

Reputation: 7602

You can share screenshot like which type of Layout needed.

You can set image view as Horizontal and Vertical like this. check below image,

enter image description here

Upvotes: 19

Related Questions