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步:看看执行结果

swift中如何正确设置UITableViewCell的UITableViewCellStyle样式属性!_第1张图片

问题出现了,明明设置了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)//方法本无对错,只是用错了地方,呜呜呜

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

swift中如何正确设置UITableViewCell的UITableViewCellStyle样式属性!_第2张图片

全剧终!!!

你可能感兴趣的:(ios开发)