简体   繁体   中英

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?

尝试将translatesAutoresizingMaskIntoConstraints设置为false

视图完全加载后,执行此操作

button.center = imageView.center

Have you tried:

button.center = imageView.center 

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

尝试.center属性,例如

myButton.center = self.image.center;

Try this

button.frame = imageV.frame

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM