轮播图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
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值