iOS之如何处理TableView cell内容不一致以及cell复用重叠的问题

来源:互联网 发布:bios密码 作用 知乎 编辑:程序博客网 时间:2024/04/28 08:52

1.问题描述:自己在做之前iOS项目之Swfit新闻App的时候,发现解析出来的Json串中的model数据存在不一致的情况,就是说有的cell有label和图片,有的cell仅仅只有label。那如何处理这种情况呢?

   解决方案:我在用Alamofire网络库对url进行解析的时候,对解析出来的数据会进行一次判断,如果某一项解析出来的imageUrl为nil的话,我会对model中对应的某项的imageUrl设置为”empty”,然后在TableView的绘制cell的回调方法中对某一行的cell进行赋值的时候,对imageUrl进行判断如果url为empty,则只为该cell的label进行赋值运算,反之则都赋值。这样就可以处理cell中内容不一致的情况。部分代码如下:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {                let initIdentifier = "MyThemeCell"                var cell = tableView.dequeueReusableCellWithIdentifier(initIdentifier) as? ThemeDataTableViewCell                let url = self.item[indexPath.row].newsImageName                        if cell == nil{                    tableView.registerNib(UINib(nibName: "ThemeDataTableViewCell", bundle: nil), forCellReuseIdentifier: initIdentifier)                    cell = tableView.dequeueReusableCellWithIdentifier(initIdentifier) as? ThemeDataTableViewCell                }                //利用SDWebImage异步加载图片                if url != "empty"{                    cell!.themeImageUrl.sd_setImageWithURL(NSURL(string: url))                }                        cell!.themeLabel.text = self.item[indexPath.row].newsTitle                        return cell!    }

2.问题描述:在对cell进行绘制的时候,会对cell进行复用,这样可以提高TableView的性能。但是在这里,由于有的cell有图片有的cell没有图片,在对TableView进行上拉或者下拉的时候,会出现一个奇怪的现象—那就是之前没图片的cell竟然有图片了,而且多拉几次,图片还会发生变化,这就是cell重用所产生的问题。

解决方案:方法其实也很简单,就是在对cell进行绘制的时候,根据该cell的imageUrl的有无,来返回两种不同的cell。一种是系统自带的UITableViewCell,一种是自定义的ThemeDataTableViewCel。部分代码如下:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {                let url = self.item[indexPath.row].newsImageName        if url == "empty"{            let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")            cell.textLabel!.text = self.item[indexPath.row].newsTitle            cell.textLabel?.numberOfLines = 3            cell.textLabel?.font = UIFont.systemFontOfSize(CGFloat(15))            return cell        }else{            let initIdentifier = "MyThemeCell"            var cell = tableView.dequeueReusableCellWithIdentifier(initIdentifier) as? ThemeDataTableViewCell            if cell == nil{                tableView.registerNib(UINib(nibName: "ThemeDataTableViewCell", bundle: nil), forCellReuseIdentifier: initIdentifier)                cell = tableView.dequeueReusableCellWithIdentifier(initIdentifier) as? ThemeDataTableViewCell            }            cell!.themeImageUrl.sd_setImageWithURL(NSURL(string: url))            cell?.themeLabel.text = self.item[indexPath.row].newsTitle            cell?.selectionStyle = UITableViewCellSelectionStyle.None            return cell!        }    }</span>

3.详见代码部分(ThemeDataViewController+TableView.swift)

   源码:我的Github

0 0
原创粉丝点击