swift中如何正确设置UITableViewCell的UITableViewCellStyle样式属性!

看看我的错误三步走:

第1步    使用如下方法在ViewController中的viewDidLoad方法中用:

            tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID") 方法去注册需要复用的Cell的ID

第2步    贴一下关键代码

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        var cell: UITableViewCell? = nil
        
        cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)
        
        if cell == nil{
            cell = UITableViewCell.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: "cellID")
        }
        
        cell?.textLabel?.text = "123123"
        cell?.imageView?.image = UIImage.init(named: "ico_del.png")
        cell?.detailTextLabel?.text = "987654"
        cell?.detailTextLabel?.backgroundColor = UIColor.brown
        cell?.textLabel?.textColor = UIColor.black
        
        return cell!
    
    }

第3步:看看执行结果


问题出现了,明明设置了UITableViewCellStyle.subtitle样式

cell = UITableViewCell.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: "cellID")

可是结果事与愿违,显示的是UITableViewCellStyle.default样式!!!纳尼?????疑问

调试后发现了问题所在:

 if cell == nil{//想一想为什么这里不会被执行,cell的样式才会设置无效的
            cell = UITableViewCell.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: "cellID")
        }

这段代码压根都没有机会去执行!!!原因是在上述第一步中已经注册过了需要复用Cell的ID,然后执行

cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)

cell结果自然不会为nil,想象中如此,哈哈!别高兴太早偷笑偷笑偷笑

(---------------------不割一下心里不爽大笑----------------------------)

那动手尝试一下看是不是想象中的结果:

果断删掉ViewController中的viewDidLoad中的注册方法

tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")//删掉删掉

不去注册了,那么当执行代码

cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)

cell的结果应该为nil了吧,可是执行结果却直接抛异常了!!!发火发火发火

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier cellID - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

好家伙,why????oh,myGod,以前不是这样对我的啊惊讶惊讶惊讶

折腾了好久,才发现用错了方法,麻蛋!!!

正确方法:

cell = tableView.dequeueReusableCell(withIdentifier: "cellID") //切记!!!

错误的方法:

cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)//方法本无对错,只是用错了地方,呜呜呜

终于自己盼望的结果出来了,上个图,慰藉一下上天之灵


全剧终!!!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值