How to Set UITableViewCellStyleSubtitle and dequeueReusableCell in Swift?

前端 未结 13 1032
攒了一身酷
攒了一身酷 2020-12-01 05:03

I\'d like a UITableView with subtitle-style cells that use dequeueReusableCellWithIdentifier.

My original Objective-C code was

13条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 05:42

    If you'd rather avoid optionality, you can make a subclass of UITableViewCell that looks something like this:

    class SubtitleTableViewCell: UITableViewCell {
    
        override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
            super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    

    Then register it using:

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.register(SubtitleTableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
    }
    

    This allows your cell customization code to be really nice:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
    
        cell.textLabel?.text = "foo"
        cell.detailTextLabel?.text = "bar"
    
        return cell
    }
    

提交回复
热议问题