【问题标题】:Programatically constraint doesn't work inside UICollectionViewCell Swift编程约束在 UICollectionViewCell Swift 中不起作用
【发布时间】:2019-02-06 09:39:56
【问题描述】:

我尝试在UICollectionViewCell 中以编程方式查看,我认为将“以编程方式查看代码”放在UICollectionViewCell 中是明智的。

这是我的代码:

override func awakeFromNib() {
        super.awakeFromNib()

        let view = UIView()
        view.frame = CGRect.zero
        view.backgroundColor = UIColor.black

        self.contentView.addSubview(view)
        self.contentView.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            view.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 0),
            view.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: 0),
            view.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: 25),
            view.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 25),
            ])

        self.contentView.layoutIfNeeded()
    }

我想知道为什么自动布局不起作用,如果我使用手动CGRect,视图确实出现了。

【问题讨论】:

    标签: ios swift uicollectionview autolayout uicollectionviewcell


    【解决方案1】:

    这解决它只需要设置 view.translatesAutoresizingMaskIntoConstraints = false 不是内容视图

    override func awakeFromNib() {
        super.awakeFromNib()
    
        let view = UIView()
        view.frame = CGRect.zero
        view.backgroundColor = UIColor.black
    
    
        self.contentView.addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            view.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 0),
            view.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: 0),
            view.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: 25),
            view.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 25),
            ])
    }
    

    【讨论】:

      【解决方案2】:

      尝试改变 self.contentView.translatesAutoresizingMaskIntoConstraints = false 到: view.translatesAutoresizingMaskIntoConstraints = false

      您想关闭您的viewtranslatesAutoresizingMaskIntoConstraints,因为我们要对其应用autolayout

      【讨论】:

        【解决方案3】:

        第一:你不应该调用layoutIfNeeded方法,在你改变规则(约束)后,自动布局循环会为你做这个

        第二个:你应该将要布局的视图的translatesAutoresizingMaskIntoConstraints属性设置为false,所以你不应该这样做

        self.contentView.translatesAutoresizingMaskIntoConstraints = false
        

        但你应该这样做

        view.translatesAutoresizingMaskIntoConstraints = false
        

        这是因为自动调整大小的蒙版约束应用于您的 view,并带有您设置的约束。这可能并且可能会导致约束中断。

        如果这没有帮助,则提供带有自动布局错误的控制台输出。

        【讨论】:

        • 注意到了。 layoutIfNeeded 的事情非常重要,谢谢伙计
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-18
        • 1970-01-01
        • 2020-05-12
        • 2016-06-28
        • 2018-06-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多