Reputation: 593
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
Reputation: 1960
Try .center
property like
myButton.center = self.image.center;
Upvotes: 0
Reputation: 1776
Have you tried:
button.center = imageView.center
It sets the center of the button frame to that of the imageview.
Upvotes: 0
Reputation: 4675
Once your view loads completely, do this
button.center = imageView.center
Upvotes: 0
Reputation: 2341
Try to set translatesAutoresizingMaskIntoConstraints
to false
.
Upvotes: 2