簡體   English   中英

將 layoutMargins 添加到 UIStackView 中的一個元素

[英]Add layoutMargins to one element in a UIStackView

我想創建一個包含 3 個元素的垂直堆棧視圖。 我只想要第二個和最后一個元素之間有更多的空間。 所以我想添加到最后一個元素:

mylastelement.layoutMargins = UIEdgeInsets(top:30, left:0,bottom:0, right:0)

但是我的堆棧視圖中沒有應用 layoutmargins。 有沒有什么簡單的方法可以實現(我想避免修改最后一個元素的內部高度)。

編輯:我只是嘗試通過執行以下操作來增加其框架內的第二個元素高度(+50):

my2ndElementLabel.sizeToFit()
my2ndElementLabel.frame = CGRect(x:my2ndElementLabel.frame.origin.x,y:lmy2ndElementLabel.frame.origin.y,
                                 width:my2ndElementLabel.frame.width, height:my2ndElementLabel.frame.height + 50)

但它沒有效果。

EDIT2:我試圖向我的 UIStackView 添加一個隨機視圖,但該視圖被忽略了! 可能在理解 UIKit 的工作方式時遺漏了一些東西?...:

let v = UIView(frame:CGRect(x:0,y:0,width:100,height:400))
v.backgroundColor = .red
myStackView.addArrangedSubview(v)
//...

這是我做的一個擴展,有助於快速實現這樣的利潤:

extension UIStackView {

    func addArrangedSubview(_ v:UIView, withMargin m:UIEdgeInsets )
    {
        let containerForMargin = UIView()
        containerForMargin.addSubview(v)
        v.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            v.topAnchor.constraint(equalTo: containerForMargin.topAnchor, constant:m.top ),
            v.bottomAnchor.constraint(equalTo: containerForMargin.bottomAnchor, constant: m.bottom ),
            v.leftAnchor.constraint(equalTo: containerForMargin.leftAnchor, constant: m.left),
            v.rightAnchor.constraint(equalTo: containerForMargin.rightAnchor, constant: m.right)
        ])

        addArrangedSubview(containerForMargin)
    }
}

您可以做的是在第二個和第三個元素之間設置自定義間距。

myStackView.setCustomSpacing(30.0, after: my2ndElementLabel)

同樣,您可以相對於嵌入它的任何視圖的相應邊緣來約束視圖的頂部(或底部)錨點。 丑陋的東西多少有點品味問題,我發現自動布局約束易於使用且易於推理。

來自 Mac OS 而不是 iOS 的一個簡單示例:

        let button = ControlFactory.labeledButton("Filter")
        addSubview(button)
        button.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -20).isActive = true
        button.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true

這個特殊的代碼存在於視圖初始值設定項中,並在視圖中間放置一個按鈕,距離底部 20 點。

我發現自己:看起來 UIStackView 根本不適用於舊的大小調整系統(使用 .frame)。 似乎您必須限制高度和寬度,當您添加排列的子視圖時,StackView 將為您限制左/上/右/下位置。

我的第二個視圖是一個標簽:我希望文本下方有 40 的邊距。 所以我首先將標簽高度計算到它的 .frame 屬性中,並將高度限制在 frame.height + 40(= my margin)

labelDesc.sizeToFit()
labelDesc.heightAnchor.constraint(equalToConstant:40).isActive = true

我發現我自己的解決方案非常丑陋。 我確信 UIKit 提供了一種更好的方法來實現這樣一個簡單的目標,而無需制作這些 DIY 解決方案。 所以如果你習慣使用 UIKit,請告訴我是否有更好的解決方案。

考慮通過根據需要在堆棧視圖中插入大小正確的 UIView 來添加“邊距”。

如果您需要 2 個特定元素之間的 40px 邊距...添加高度約束為 40px 的 UIView。 指定clearColor背景以使其不可見。

您可以將 IBOutlets 添加到此視圖並像在堆棧視圖中的任何其他項目一樣隱藏它。

暫無
暫無

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

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