[英]How to center UIButton programmatically in UIImageView?
我正在ViewCell
编程方式创建ViewCell
,我想将UIButton
居中到UIImageView
,因此它看起来像这样:
-----------------------------
| |
| |
| Button |
| |
| |
-----------------------------
为了实现init方法中的第一个,我创建了UIImageView
和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)
然后添加一些约束,如果是按钮和图像视图,则添加以下约束:
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))
但是结果是我总是崩溃我的应用程序。
如何实现居中按钮?
尝试将translatesAutoresizingMaskIntoConstraints
设置为false
。
视图完全加载后,执行此操作
button.center = imageView.center
你有没有尝试过:
button.center = imageView.center
它将按钮框的中心设置为imageview的中心。
尝试.center
属性,例如
myButton.center = self.image.center;
尝试这个
button.frame = imageV.frame
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.