簡體   English   中英

UIButton不粘在UIView邊緣

[英]UIButtons not sticking to UIView edges

嗨,謝謝你。 我正在嘗試將兩個UIButton綁定到UIViewControllerview如下所示:

首先通過聲明它們:

fileprivate var deleteButton: UIButton = UIButton(type: .system)
fileprivate var addButton: UIButton = UIButton(type: .system)

接下來進行設置:

private func setupButtons() {

    deleteButton.setTitle("Delete", for: .normal)
    addButton.setTitle("Add", for: .normal)

    deleteButton.sizeToFit()
    addButton.sizeToFit()

    deleteButton.alpha = 1
    addButton.alpha = 1

    view.addSubview(deleteButton)
    view.addSubview(addButton)

    view.addConstraint(NSLayoutConstraint(item: deleteButton,
                                          attribute: .leading,
                                          relatedBy: .equal,
                                          toItem: view,
                                          attribute: .leading,
                                          multiplier: 1.0,
                                          constant: 0))

    view.addConstraint(NSLayoutConstraint(item: deleteButton,
                                          attribute: .bottom,
                                          relatedBy: .equal,
                                          toItem: view,
                                          attribute: .bottom,
                                          multiplier: 1.0,
                                          constant: 0))

    view.addConstraint(NSLayoutConstraint(item: addButton,
                                          attribute: .trailing,
                                          relatedBy: .equal,
                                          toItem: view,
                                          attribute: .trailing,
                                          multiplier: 1.0,
                                          constant: 0))

    view.addConstraint(NSLayoutConstraint(item: addButton,
                                          attribute: .bottom,
                                          relatedBy: .equal,
                                          toItem: view,
                                          attribute: .bottom,
                                          multiplier: 1.0,
                                          constant: 0))

}

但是運行模擬器會將兩個UIButton粘在左上角,這是分配給它們的默認CGRect框架。

您知道我在做什么錯嗎? 我覺得我已經接近了,但也許與重繪視圖有關嗎?

!

您應該將translatesAutoresizingMaskIntoConstraints設置為false

// before activate constraint

deleteButton.translatesAutoresizingMaskIntoConstraints = false
addButton.translatesAutoresizingMaskIntoConstraints = false

另外,您必須設置isActive = true而不是使用addConstraint方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM