在 CollectionViewCell 中居中 UIImegaeView

Center UIImegaeView in CollectionViewCell

我尝试创建一个以图像为中心的 collectionView 单元格

我的 class 看起来像:

import Foundation
import UIKit

class MenuCell: UICollectionViewCell{
    

    let image:UIImageView = {
        
        let i = UIImageView()
        i.image = (UIImage(named: "mainMenu"))
        i.contentMode = .scaleAspectFit
        return i
        
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        

    }
    
    required init?(coder: NSCoder) {
        fatalError()
    }
    
    func setupCell(){
        addSubview(image)

        let centerXConst = NSLayoutConstraint(item: image, attribute: .centerX, relatedBy: .equal, toItem: self.contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)
        let centerYConst = NSLayoutConstraint(item: image, attribute: .centerY, relatedBy: .equal, toItem: self.contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)
        
    
        image.addConstraints([centerXConst, centerYConst])
        NSLayoutConstraint.activate([image.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor), image.centerXAnchor.constraint(equalTo: contentView.centerXAnchor)])


    }
    
}

但是当我 运行 它给了我一个错误

When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on

如我所见,我正常添加constrant。

更新: 更改功能代码。不知道=(

func setupCell(){
    contentView.addSubview(image)

    let centerXConst = NSLayoutConstraint(item: image, attribute: .centerX, relatedBy: .equal, toItem: self.contentView, attribute: .centerX, multiplier: 1.0, constant: 0.0)
    let centerYConst = NSLayoutConstraint(item: image, attribute: .centerY, relatedBy: .equal, toItem: self.contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)

    NSLayoutConstraint.activate([centerXConst, centerYConst])


}

As I see, I add constrant normally.

嗯,你看错了。您将图像视图固定到单元格内容视图,但您没有将图像视图 放入 内容视图。你需要。变化

addSubview(image)

contentView.addSubview(image)

此外,正如评论中指出的那样,将中心 x 固定到中心 y 是没有意义的。更正如下:

let centerXConst = NSLayoutConstraint(item: image, attribute: .centerX, relatedBy: .equal, toItem: self.contentView, attribute: .centerX, multiplier: 1.0, constant: 0.0)
let centerYConst = NSLayoutConstraint(item: image, attribute: .centerY, relatedBy: .equal, toItem: self.contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)

此外,您忘记告诉图像视图不要将其自动调整掩码转换为约束。

最后,不要同时添加和激活约束。激活添加,您显然不知道要将约束添加到哪个视图。所以删除这一行:

image.addConstraints([centerXConst, centerYConst])