简体   繁体   English

如何在UIImageView中以编程方式使UIButton居中?

[英]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: 我正在ViewCell编程方式创建ViewCell ,我想将UIButton居中到UIImageView ,因此它看起来像这样:

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

To achieve that first in init method I create UIImageView and UIButton : 为了实现init方法中的第一个,我创建了UIImageViewUIButton

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. 它将按钮框的中心设置为imageview的中心。

尝试.center属性,例如

myButton.center = self.image.center;

Try this 尝试这个

button.frame = imageV.frame button.frame = imageV.frame

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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