【问题标题】:How to make custom class for auto layouts?如何为自动布局制作自定义类?
【发布时间】:2019-03-20 18:02:31
【问题描述】:

就像我们为 UIButton 和 UIKit 的其他项目制作自定义类一样。

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

如果做不到,请评论为什么做不到?

【问题讨论】:

标签: ios iphone swift autolayout


【解决方案1】:

以下扩展可用于您的要求

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)

label.anchor(top: nil, left: customCell.leftAnchor, bottom: customCell.bottomAnchor, right: customCell.rightAnchor, topConstant: 0, leftConstant: 22, bottomConstant: 0, rightConstant: 22, widthConstant: width, heightConstant: btnHeigght)

【讨论】:

    猜你喜欢
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 2023-04-04
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    相关资源
    最近更新 更多