如何为自动布局创建自定义类?

时间:2018-10-16 08:48:23

标签: ios iphone swift autolayout

就像我们为UIButton和UIKit的其他项创建自定义类一样。

我们只需在该类中定义布局,然后像其他自定义类一样进一步使用它们即可。

如果不可能发生,请评论为什么不能完成?

1 个答案:

答案 0 :(得分:0)

下面的扩展名可以用于您的要求

for contract in Contract.objects.with_first_commissioning():
    contract._turbine_age()...

for contract in Contract.objects.with_windfarms():
    contract._contracted_windfarm_name()...

extension UIView {

public func anchor(top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) {

    translatesAutoresizingMaskIntoConstraints = false

    var anchors = [NSLayoutConstraint]()

    if let top = top {
        anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
    }

    if let left = left {
        anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
    }

    if let bottom = bottom {
        anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
    }

    if let right = right {
        anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
    }

    if widthConstant > 0 {
        anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
    }

    if heightConstant > 0 {
        anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
    }

    anchors.forEach({$0.isActive = true})
}



public func anchor(centerX: NSLayoutXAxisAnchor? = nil, centerY: NSLayoutYAxisAnchor? = nil, xConstant: CGFloat = 0, yConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) {

    self.translatesAutoresizingMaskIntoConstraints = false

    var anchors = [NSLayoutConstraint]()

    if let centerX = centerX {
        anchors.append(centerXAnchor.constraint(equalTo: centerX, constant: xConstant))
    }

    if let centerY = centerY {
        anchors.append(centerYAnchor.constraint(equalTo: centerY, constant: yConstant))
    }

    if widthConstant > 0 {
        anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
    }

    if heightConstant > 0 {
        anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
    }

    anchors.forEach({$0.isActive = true})
}

}

label.anchor(centerX: view.centerXAnchor, centerY: view.centerYAnchor, xConstant: 20, yConstant: 5, widthConstant: screenSize.width, heightConstant: height1)