Tajnero
Tajnero

Reputation: 593

How to center UIButton programmatically in UIImageView?

I'm creating ViewCell programmatically and I want to center UIButton to UIImageView, so it would look like this:

 -----------------------------
|                             |
|                             |
|            Button           |
|                             |
|                             |
 -----------------------------

To achieve that first in init method I create UIImageView and UIButton:

let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.layer.masksToBounds = true
imageView.isUserInteractionEnabled = true

let button = UIButton(type: .custom)
button.setImage(UIImage(named: "button_image"), for: .normal)
button.contentMode = .center
button.frame = CGRect(x: 0, y: 0, width: 42, height: 42)

And then I add some constraints, in case of button and imageview I added these constraints:

button.addConstraint(NSLayoutConstraint(item: button, attribute: .centerX, relatedBy: .equal, toItem: imageView, attribute: .centerX, multiplier: 1, constant: 0))
button.addConstraint(NSLayoutConstraint(item: button, attribute: .centerY, relatedBy: .equal, toItem: imageView, attribute: .centerY, multiplier: 1, constant: 0))

But as result I always crash my app.

How can I achieve centered button?

Upvotes: 0

Views: 1143

Answers (5)

Sayali Shinde
Sayali Shinde

Reputation: 96

Try this

button.frame = imageV.frame

Upvotes: 0

TheHungryCub
TheHungryCub

Reputation: 1960

Try .center property like

myButton.center = self.image.center;

Upvotes: 0

DrPatience
DrPatience

Reputation: 1776

Have you tried:

button.center = imageView.center 

It sets the center of the button frame to that of the imageview.

Upvotes: 0

itsji10dra
itsji10dra

Reputation: 4675

Once your view loads completely, do this

button.center = imageView.center

Upvotes: 0

Artem Novichkov
Artem Novichkov

Reputation: 2341

Try to set translatesAutoresizingMaskIntoConstraints to false.

Upvotes: 2

Related Questions