首页 文章

自定义UITableViewCell无法正常工作

提问于
浏览
0

我想制作一个可以有很多列的自定义UITableViewCell . 一个是UILabel,一个是UIButton . 我想通过说我只是通过按住控制键并将UI项目拖到我的代码来创建我的IBOutlets来开始这个 . 所以这意味着我的所有IBOutlet都正确连接 . 我的问题是UILabel和UIButton在我的任何细胞中都不可见 . 细胞在那里,但没有别的 .

enter image description here

class CustomTableViewCell: UITableViewCell{
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var button: UIButton!
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{

    var items: [Strings] = ["one", "two", "three"]
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad(){
        super.viewDidLoad()
        self.tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "cell")
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return items.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell:CustomTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell")! as! CustomTableViewCell

        cell.label?.text = self.items[indexPath.row]

        return cell
    }
}

我将UITableView的数据源和委托设置为ViewController,我正确设置了单元重用ID,UILabel和UIButton都设置了约束 . 我觉得我错过了什么 .

2 回答

  • 0

    must not 注册单元格 - 当使用原型单元格时 - 你 must 重新加载表格视图 .

    更换

    override func viewDidLoad(){
        super.viewDidLoad()
        self.tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "cell")
    }
    

    override func viewDidLoad(){
        super.viewDidLoad()
        self.tableView.reloadData()
    }
    
  • 1

    缺少那些:

    self.tableView.delegate = self
    self.tableview.datasource = self
    

    希望这可以帮助!

相关问题