轮播图Cell没有正确布局
class MyCyclePagerViewCell: UICollectionViewCell {
var imageView: UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
// 初始化 imageView,确保它占满整个 cell
imageView = UIImageView(frame: self.bounds)
imageView.contentMode = .scaleAspectFill
self.contentView.addSubview(imageView)
// print("cell frame: \(self.frame)")
// print("cell bounds: \(self.bounds)")
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 用于设置图片
func setImage(_ image: UIImage) {
imageView.image = image
// print("image frame: \(self.frame)")
// print("image bounds: \(self.bounds)")
}
}
虽然设置了 contentMode = .scaleAspectFill,这意味着图片会等比缩放填充 imageView,但由于没有设置约束或布局,imageView 可能默认会被拉伸或者没有占满整个 cell。
可以调整 MyCyclePagerViewCell 的 imageView 布局,确保它能够填满整个 cell。可以通过使用 TGLinearLayout 来更好地布局,或者使用自动布局来约束 imageView 占满整个 cell。
class MyCyclePagerViewCell: UICollectionViewCell {
var imageView: UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
// 创建 TGLinearLayout 容器
let linearLayout = TGLinearLayout(.vert) // 使用垂直布局
linearLayout.frame = self.bounds
linearLayout.tg_width.equal(.fill) // 宽度填充父容器
linearLayout.tg_height.equal(.fill) // 高度填充父容器
self.contentView.addSubview(linearLayout)
// 创建 imageView 并设置属性
imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true // 保证图片不会溢出 cell 的边界
linearLayout.addSubview(imageView)
// 使用 TGLinearLayout 来自动布局 imageView
imageView.tg_width.equal(.fill)
imageView.tg_height.equal(.fill)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 用于设置图片
func setImage(_ image: UIImage) {
imageView.image = image
}
}