ios - 在 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])
}
解决方案
如我所见,我通常添加常量。
嗯,你看错了。您将图像视图固定到单元格内容视图,但您没有将图像视图放在内容视图中。你需要。改变
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])
推荐阅读
- reactjs - 为什么在尝试使用返回值创建图表时出现三个错误?
- airflow - 将“snowflake-connector-python”安装到 GCP Cloud Composer 时出错
- xcode - MacOS 应用程序屏幕尺寸
- swift - 如何创建不可变的惰性属性?
- cmd - 如何终止批处理文件
- python - 即使 foreign_keys 为 ON,FOREIGN KEY 约束也会失败
- javascript - 是否可以使用带有 Javascript 的 HTML 的 CANVAS 上下文(ctx)来制作字体选择器?
- android - Admob 广告停止工作 - iOS14 是否也影响 android 版本控制?
- kotlin - 在接口方法中获取当前事务句柄
- c - * 之间有什么区别
和 * 在 C 中?