除非缓存了图像,否则TableView Cell的格式不正确

如何解决除非缓存了图像,否则TableView Cell的格式不正确

我的表格视图出现问题,即在缓存图像之前,单元格无法正确定向,并且只有当我返回页面并缓存了图像时,它们才能正确定向。这是我正在谈论的示例,第一个图像是我第一次访问该页面时,并且具有将图像存储在图像缓存中的功能,第二个图像是我在导航至其他位置后返回该页面时,并且图像被缓存。

格式错误:

enter image description here

格式正确:

enter image description here

我知道这是非常微妙的区别 与它的外观 但我很想弄清楚这一点,并理解为什么会发生这种情况

我的单元格恒定高度为85,这是相关代码:

func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//Indexing part I left out dw about this



        let cell = discountTableView.dequeueReusableCell(withIdentifier: self.discountCellId,for: indexPath) as! DiscountCell
        cell.textLabel?.text = discount.retailerName
        cell.detailTextLabel?.text = discount.matchedFirstName + " " + discount.matchedLastName
        cell.profileImageView.image = UIImage.gif(name: "imageLoading")!
        grabImageWithCache(discount.retailerImageLink) { (profilePic) in
            cell.profileImageView.image = profilePic
        }
        //Adding second Image
        cell.matchImageView.image = UIImage.gif(name: "imageLoading")!
        grabImageWithCache(discount.matchedProfileImage) { (matchProfilepic) in
            cell.matchImageView.image = matchProfilepic
        }
        //declare no selection style for cell (avoid gray highlight)
        cell.selectionStyle = .none
        //format the cell's curvature
        cell.layer.cornerRadius = 38
        return cell
    }

**我很好奇为什么缓存图像时单元格的高度似乎会发生变化,因为高度被设置为一个常数,所以我不知道为什么它会发生变化。当我打印单元格的高度时,它说也是两次85 ...

UITableViewCell类:

class DiscountCell: UITableViewCell {

    override func layoutSubviews() {
        super.layoutSubviews()
        //vertical spacing between cells
        let padding = UIEdgeInsets(top: 0,left: 0,bottom: 7,right: 0)
        bounds = bounds.inset(by: padding)
        
        textLabel?.frame = CGRect(x: 120,y: textLabel!.frame.origin.y-10,width: textLabel!.frame.width,height: textLabel!.frame.height)
        detailTextLabel?.frame = CGRect(x: 120,y: detailTextLabel!.frame.origin.y,width: detailTextLabel!.frame.width,height: detailTextLabel!.frame.height)
        //spacing between cells
        let margins = UIEdgeInsets(top: 0,bottom: 85,right: 0)
        contentView.frame = contentView.frame.inset(by: margins)

    }
    
    //sets a placeholder imageview
    let profileImageView: UIImageView = {
        let imageView = UIImageView ()
        imageView.image = UIImage(named: "failed")
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.layer.cornerRadius = 35
        imageView.layer.masksToBounds = true
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        imageView.layer.borderWidth = 2
        imageView.layer.borderColor = #colorLiteral(red: 0.9725490196,green: 0.9725490196,blue: 0.9725490196,alpha: 1)
        return imageView
    }()
    //PlaceHolder imageview for match
    let matchImageView:UIImageView = {
        let imageView = UIImageView ()
        imageView.image = UIImage(named: "failed")
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.layer.cornerRadius = 35
        imageView.layer.masksToBounds = true
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
    
    override init(style: UITableViewCell.CellStyle,reuseIdentifier: String?) {
        super.init(style: .subtitle,reuseIdentifier: reuseIdentifier)
        
        addSubview(matchImageView)
        addSubview(profileImageView)
        //Setting Profile Pic anchors
        profileImageView.leftAnchor.constraint(equalTo: self.leftAnchor,constant: 5).isActive = true
        profileImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
        profileImageView.widthAnchor.constraint(equalToConstant: 70).isActive = true
        profileImageView.heightAnchor.constraint(equalToConstant: 70).isActive = true
        //Setting Match Anchors
        matchImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
        matchImageView.widthAnchor.constraint(equalToConstant: 70).isActive = true
        matchImageView.heightAnchor.constraint(equalToConstant: 70).isActive = true
        matchImageView.leftAnchor.constraint(equalTo: profileImageView.leftAnchor,constant: 35).isActive = true
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

我相信我已经解决了这个问题,我注意到两次单元格之间的间隔不一致,所以我认为问题在于这些代码行

        //vertical spacing between cells
        let padding = UIEdgeInsets(top: 0,right: 0)
        bounds = bounds.inset(by: padding)

我不确定该怎么做,因为我看到教程说要更改contentviews实例,但是当我这样做时,它没有效果,而且我看到一些事情说iOS 11改变了您这样做的方式,但是并没有能够找到实际解决此问题的方法。

解决方法

情侣笔记...

修改单元格的bounds或其contentView并不是一个好主意。 UIKit将它们用于很多事情(例如在实现表编辑时调整内容)。

单元格子视图应添加到单元格的contentView,而不是单元格本身。同样,由于表视图如何依赖该层次结构。

您可以使用UIViewUIImageView子类来为您处理“四舍五入”。例如:

class RoundImageView: UIImageView {
    override func layoutSubviews() {
        layer.cornerRadius = bounds.size.height * 0.5
    }
}
class RoundEndView: UIView {
    override func layoutSubviews() {
        layer.cornerRadius = bounds.size.height * 0.5
    }
}

这是一个完整的实现:

class RoundImageView: UIImageView {
    override func layoutSubviews() {
        layer.cornerRadius = bounds.size.height * 0.5
    }
}
class RoundEndView: UIView {
    override func layoutSubviews() {
        layer.cornerRadius = bounds.size.height * 0.5
    }
}

class DiscountCell: UITableViewCell {
    
    // "Holder" view... contains all other UI elements
    // use RoundEndView so it handles the corner radius by itself
    let holderView: RoundEndView = {
        let v = RoundEndView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .white
        return v
    }()
    
    //sets a placeholder imageview
    // use RoundImageView so it handles the corner radius by itself
    let profileImageView: RoundImageView = {
        let imageView = RoundImageView()
        imageView.image = UIImage(named: "failed")
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.layer.masksToBounds = true
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        imageView.layer.borderWidth = 2
        imageView.layer.borderColor = #colorLiteral(red: 0.9725490196,green: 0.9725490196,blue: 0.9725490196,alpha: 1)
        return imageView
    }()
    
    //PlaceHolder imageview for match
    // use RoundImageView so it handles the corner radius by itself
    let matchImageView: RoundImageView = {
        let imageView = RoundImageView()
        imageView.image = UIImage(named: "failed")
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.layer.masksToBounds = true
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
    
    let mainLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.font = UIFont.systemFont(ofSize: 17.0,weight: .regular)
        return v
    }()
    
    let subLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.font = UIFont.systemFont(ofSize: 14.0,weight: .regular)
        return v
    }()
    
    override init(style: UITableViewCell.CellStyle,reuseIdentifier: String?) {
        super.init(style: .subtitle,reuseIdentifier: reuseIdentifier)
        commonInit()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    
    func commonInit() -> Void {
        
        backgroundColor = .clear
        
        contentView.addSubview(holderView)
        
        holderView.addSubview(matchImageView)
        holderView.addSubview(profileImageView)
        holderView.addSubview(mainLabel)
        holderView.addSubview(subLabel)
        
        NSLayoutConstraint.activate([

            // holder view constraints Top 5 pts from contentView Top
            holderView.topAnchor.constraint(equalTo: contentView.topAnchor,constant: 5.0),// Leading 12 pts from contentView Leading
            holderView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor,constant: 12.0),// Trailing 5 pts from contentView Trailing
            holderView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor,constant: -5.0),// 5 pts from contentView Bottom (use lessThanOrEqualTo to avoid auto-layout warnings)
            holderView.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor,//Setting Profile Pic anchors - Top and Leading 5 pts from Top and Leading of Holder view
            profileImageView.topAnchor.constraint(equalTo: holderView.topAnchor,constant: 5),profileImageView.leadingAnchor.constraint(equalTo: holderView.leadingAnchor,// Botom 5 pts from contentView Bottom - this will determine the height of the Holder view
            profileImageView.bottomAnchor.constraint(equalTo: holderView.bottomAnchor,constant: -5),// width 70 pts,height equal to width (keeps it "round")
            profileImageView.widthAnchor.constraint(equalToConstant: 70.0),profileImageView.heightAnchor.constraint(equalTo: profileImageView.widthAnchor),//Setting Match Pic Anchors - 35 pts from Profile Leading,centerY to Profile
            matchImageView.leadingAnchor.constraint(equalTo: profileImageView.leadingAnchor,constant: 35),matchImageView.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor,constant: 0.0),// same width and height as Profile
            matchImageView.widthAnchor.constraint(equalTo: profileImageView.widthAnchor),matchImageView.heightAnchor.constraint(equalTo: profileImageView.heightAnchor),//Setting Main Label Anchors - Top equal to Top of Match image
            mainLabel.topAnchor.constraint(equalTo: matchImageView.topAnchor,// Leading 12 pts from Match image Trailing
            mainLabel.leadingAnchor.constraint(equalTo: matchImageView.trailingAnchor,// prevent Trailing from going past holder view Trailing
            mainLabel.trailingAnchor.constraint(equalTo: holderView.trailingAnchor,constant: -16.0),//Setting Sub Label Anchors - Top 8 pts from Main label Bottom
            subLabel.topAnchor.constraint(equalTo: mainLabel.bottomAnchor,constant: 8.0),// Leading and Trailing equal to Main label Leading / Trailing
            subLabel.leadingAnchor.constraint(equalTo: mainLabel.leadingAnchor,subLabel.trailingAnchor.constraint(equalTo: mainLabel.trailingAnchor,])
        
    }
}

// example Discount object struct
struct Discount {
    var retailerName: String = ""
    var matchedFirstName: String = ""
    var matchedLastName: String = ""
    var matchedProfileImage: String = ""
    var retailerImageLink: String = ""
}

class DiscountViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
    
    let discountTableView = UITableView()
    
    let discountCellId = "dcID"
    
    var myData: [Discount] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // a little sample data
        var d = Discount(retailerName: "Cup & Cone",matchedFirstName: "Kara",matchedLastName: "Tomlinson",matchedProfileImage: "pro1",retailerImageLink: "")
        myData.append(d)
        d = Discount(retailerName: "Cup & Cone",matchedFirstName: "Sophie",matchedLastName: "Turner",matchedProfileImage: "pro2",retailerImageLink: "")
        myData.append(d)
        d = Discount(retailerName: "Another Retailer",matchedFirstName: "WanaB3",matchedLastName: "Nerd",matchedProfileImage: "pro3",retailerImageLink: "")
        myData.append(d)

        
        discountTableView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(discountTableView)
        let g = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            discountTableView.topAnchor.constraint(equalTo: g.topAnchor,constant: 20.0),discountTableView.leadingAnchor.constraint(equalTo: g.leadingAnchor,discountTableView.trailingAnchor.constraint(equalTo: g.trailingAnchor,constant: -20.0),discountTableView.bottomAnchor.constraint(equalTo: g.bottomAnchor,])
        
        view.backgroundColor = UIColor(red: 1.0,green: 0.9,blue: 0.7,alpha: 1.0)
        discountTableView.backgroundColor = UIColor(red: 0.66,green: 0.66,blue: 0.9,alpha: 1.0)
        discountTableView.separatorStyle = .none

        discountTableView.delegate = self
        discountTableView.dataSource = self
        
        discountTableView.register(DiscountCell.self,forCellReuseIdentifier: discountCellId)
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
        return myData.count
    }
    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //Indexing part I left out dw about this
        
        let discount = myData[indexPath.row]
        
        let cell = discountTableView.dequeueReusableCell(withIdentifier: self.discountCellId,for: indexPath) as! DiscountCell
        
        cell.mainLabel.text = discount.retailerName
        cell.subLabel.text = discount.matchedFirstName + " " + discount.matchedLastName

        // add first image
        if let img = UIImage(named: "imageLoading") {
            cell.profileImageView.image = img
        }
        // use your custom image funcs
        //cell.profileImageView.image = UIImage.gif(name: "imageLoading")!
        //grabImageWithCache(discount.retailerImageLink) { (profilePic) in
        //  cell.profileImageView.image = profilePic
        //}

        //Adding second Image
        if let img = UIImage(named: discount.matchedProfileImage) {
            cell.matchImageView.image = img
        }
        // use your custom image funcs
        //cell.matchImageView.image = UIImage.gif(name: "imageLoading")!
        //grabImageWithCache(discount.matchedProfileImage) { (matchProfilepic) in
        //  cell.matchImageView.image = matchProfilepic
        //}
        
        //declare no selection style for cell (avoid gray highlight)
        cell.selectionStyle = .none

        return cell
    }
    
}

结果:

enter image description here

enter image description here

,

您的细胞呈药丸状,这意味着您可以通过cell.layer.cornerRadius = cell.frame.height / 2来达到相同的效果。接下来,您应该为profileImageView使用顶部和底部约束,以便它强制单元格具有特定的填充,而不是尝试自己创建填充。问题是,当缓存图像时,单元格的高度有些变化,不知道是什么原因造成的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-