当前位置: 首页 > news >正文

轮播图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
    }
}

相关文章:

  • 安装Liunx(CentOS-6-x86_64)系统
  • 【信息系统项目管理师-案例真题】2010下半年案例分析答案和详解
  • 网页制作08-html,css,javascript初认识のhtml使用框架结构,请先建立站点!
  • spring-data-mongoDB
  • UML中各箭头符号解释
  • 告别阻塞,迎接高效:掌握 AsyncIOScheduler 实现异步任务调度
  • vue2版本elementUI的table分页实现多选逻辑
  • 基于SpringBoot + Vue的共享汽车(单车)管理系统设计与实现+毕业论文+开题报告+指导搭建视频
  • Github更新本地仓库到远程总是失败文件过大,如何解决。
  • 设计模式教程:策略模式(Strategy Pattern)
  • C++程序员内功修炼——Linux C/C++编程技术汇总
  • RK3399 Android7 Ethernet Tether功能实现
  • 香港多IP站群服务器
  • 【时时三省】(C语言基础)顺序程序设计举例
  • 【无人集群系列---大疆无人集群技术进展、技术路线与未来发展方向】
  • 汽车零部件工厂如何通过ESD监控系统闸机提升产品质量
  • 如何在 CMake 上设置新项目以获得成功
  • 起猛了,植物大战僵尸出了金铲铲模式?
  • Linux 核心架构与组件(2025更新中)
  • 回溯算法之组合和排列问题
  • 我使馆就中国公民和企业遭不公正待遇向菲方持续提出严正交涉
  • 夜读丨母亲为燕子打开家门
  • “免签圈”扩容,旅游平台:今年以来巴西等国入境游订单显著增加
  • 上海静安将发放七轮文旅消费券,住宿券最高满800元减250元
  • 外交部:正确认识和对待历史是检验日本能否恪守和平发展承诺的重要标准
  • 第四届长三角国际应急博览会开幕,超3000件前沿装备技术亮相