簡體   English   中英

以編程方式為 UIButton 創建約束

[英]Programmatically create constraints for UIButton

我有一個UIViewController ,其中包含一個UIScrollView ,然后包含一個UIImageView. 我以編程方式創建了一個UIButton (我的項目不包含故事板/筆尖)。

我希望按鈕保持固定在屏幕的右上角,但我不知道如何手動創建正確的約束。

我認為以下方法會起作用,但按鈕的位置仍然不正確。 我還需要在viewWillLayoutSubviews()做些什么嗎?

// Setup constraints, in viewDidLoad()
let viewDict = ["shareButton": self.shareButton!]
self.scrollView.addConstraints(NSLayoutConstraint.constraints(
                             withVisualFormat: "H:[shareButton]|", 
                                      options: [], 
                                      metrics: nil, 
                                        views: viewDict))

self.scrollView.addConstraints(NSLayoutConstraint.constraints(
                             withVisualFormat: "V:|[shareButton]",
                                      options: [], 
                                      metrics: nil, 
                                        views: viewDict))

如果滾動視圖是應用程序的頂級視圖,則無法實現此布局。 滾動視圖和滾動視圖的后代之間的約束總是約束滾動視圖的滾動內容內的后裔。 有關更多詳細信息,請參閱技術說明 TN2154 UIScrollView 和自動布局 技術說明准確解釋了您需要做什么:

請注意,您可以通過在視圖和滾動視圖子樹之外的視圖(例如滾動視圖的超級視圖)之間創建約束,使滾動視圖的子視圖看起來浮動(而不是滾動)在其他滾動內容上。

您需要像這樣安排您的視圖層次結構:

+-- UIView (view controller's root view)
    |
    +-- UIScrollView
        |
        +-- UIImageView
        |
        +-- UIButton

或者像這樣:

+-- UIView (view controller's root view)
    |
    +-- UIScrollView
    |   |
    |   +-- UIImageView
    |
    +-- UIButton

然后(使用這些安排中的任何一個)您可以將按鈕限制為根視圖,如下所示:

NSLayoutConstraint.activateConstraints([
    shareButton.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor, constant:-8),
    shareButton.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 8)
])

如果你在代碼中做所有事情,這兩個約束不足以完全指定 UIIMageView 的位置,在這兩個約束中至少添加一個寬度和重量(例如修改你已經擁有的約束H:[shareButton(100)]| )。

另外,我建議使用shareButton.translatesAutoresizingMaskIntoConstraints = false禁用 autoresizemask 到約束的轉換。

對於此布局,您無需在viewWillLayoutSubviews執行任何操作。

您可以在課程結束時添加此擴展程序

extension UIView {


    func addCosntraintsWithFormat(format: String, views: UIView...) {

        var viewsDictionary = [String: UIView]()

        for (index, view) in views.enumerate() {
            let key = "v\(index)"
            viewsDictionary[key] = view
        }

        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
    }
}

然后你可以添加這樣的約束

self.scrollView.addConstraintsWithFormat("H:[v0(\(YourWidthConstant))]|", views: shareButton)
self.scrollView.addConstraintsWithFormat("V:|[v0(\(YourHeightConstant))]", views: shareButton)

這個信息來源是這個

暫無
暫無

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

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