[英]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.