swift - 使用自动布局以编程方式将自定义 UIView 与 View 对齐

标签 swift

我正在尝试使用自动布局将自定义 UIView 与 View 中心对齐,但出现空白屏幕。

有人可以告诉我我的代码哪里不正确吗?


我的 Controller 的代码:

import UIKit

class TestViewController: UIViewController{

    var margin: UILayoutGuide!

    override func viewDidLoad() {
        super.viewDidLoad()
        margin = self.view.layoutMarginsGuide

        let size = CGRect.init(x: 0, y: 0, width: 200, height: 100)
        let sq1 = Square.init(frame: size, color: UIColor.blue)

        view.addSubview(sq1)

        sq1.translatesAutoresizingMaskIntoConstraints = false
        sq1.centerXAnchor.constraint(equalTo: margin.centerXAnchor).isActive = true
        sq1.topAnchor.constraint(greaterThanOrEqualTo: margin.topAnchor, constant: 20).isActive = true

        sq1.leadingAnchor.constraint(greaterThanOrEqualTo: margin.leadingAnchor, constant: 20).isActive = true
        sq1.trailingAnchor.constraint(greaterThanOrEqualTo: margin.trailingAnchor, constant: 20).isActive = true


    }

}

我的自定义 View 的代码:

class Square: UIView{

    init(frame: CGRect, color: UIColor) {
        super.init(frame: frame)

        makeSquare(frame: frame, colour: color)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func makeSquare(frame: CGRect, colour: UIColor){
        self.layer.frame = self.bounds
        self.layer.backgroundColor = colour.cgColor
    }

}

最佳答案

你需要一个高度限制,也不要混合框架布局和自动布局你应该使用它们中的任何一个

sq1.heightAnchor.constraint(equalToConstant:200).isActive = true

此外,如果您设置前导和尾随

sq1.leadingAnchor.constraint(greaterThanOrEqualTo: margin.leadingAnchor, constant: 20).isActive = true
sq1.trailingAnchor.constraint(greaterThanOrEqualTo: margin.trailingAnchor, constant: 20).isActive = true

那么就不需要centerX了

sq1.centerXAnchor.constraint(equalTo: margin.centerXAnchor).isActive = true

NSLayoutConstraint.activate([
    sq1.topAnchor.constraint(equalTo: margin.topAnchor, constant: 20),
    sq1.leadingAnchor.constraint(equalTo: margin.leadingAnchor, constant: 20),
    sq1.trailingAnchor.constraint(equalTo: margin.trailingAnchor, constant: -20), 
    sq1.heightAnchor.constraint(equalToConstant: 200) 
])

enter image description here

关于swift - 使用自动布局以编程方式将自定义 UIView 与 View 对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56951268/

相关文章:

ios - 在几个应用程序中用新的 Swift 替换旧的 Objective-c 库

ios - Realm 中 NSData 的可选列表 - Swift

ios - Xcode 10、Swift 4 - 如何跨多个 View Controller 传输数据?

objective-c - 在 Swift 中将 NSData 转换为 Data,现在当我尝试将字节转换为 [UInt] 时出现崩溃

swift - 为什么(self.account.text?.isEmpty)!需要 '!'

Swift didSet for var 在子级中使用 @Binding 进行更改

ios - 将对象用作核心数据对象字段类型

ios - 相同位置 2 个按钮在 swift 中?

ios - 绑定(bind)必须有可选类型 Swift

swift - 使用 CoreImage 生成条码 CI 39