首页 > 解决方案 > 在 CollectionViewCell 中居中 UIImegaeView

问题描述

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

我的课看起来像:

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)])


    }
    
}

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

添加到视图时,约束的项必须是该视图(或视图本身)的后代。如果在组装视图层次结构之前需要解决约束,这将崩溃。打断

如我所见,我通常添加常量。

UPD:更改功能代码。不会吧=(

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])


}

标签: iosswiftviewuiviewuiimageview

解决方案


如我所见,我通常添加常量。

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

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])

推荐阅读