【发布时间】:2017-07-03 18:10:43
【问题描述】:
我已按照stackoverflow question & answer 作为指南在表格视图中创建自定义单元格(未在情节提要中添加原型单元格),但是我无法使用自定义单元格创建表格视图,我只是得到行的空单元格。我确实查看了其他 SO 问题,但它们没有帮助。
我认为我注册单元格的方式有问题。
(仅供参考:当我将原型单元格添加到我的表格视图并为其分配一个类和单元格 ID 时,如果我随后禁用 tableView.register(AppointmentTVCell.self, forCellReuseIdentifier: cellId) 它可以工作,我对此不感兴趣,因为我想尽量减少对 IB 的使用)
下面是我在故事板中的 tableViewController,已为其分配了一个表视图类 AppointmentsTVC
下面是我的表格视图控制器代码
class AppointmentsTVC: UITableViewController {
let cellId = "reuseIdentifier"
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(AppointmentTVCell.self, forCellReuseIdentifier: cellId)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 2
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("Cell for Row at func called")
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! AppointmentTVCell // Creating a cell
cell.caseId.text = "123456"
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150.0
}
}
下面是自定义表格视图单元格的代码
class AppointmentTVCell: UITableViewCell {
let caseId: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14)
label.frame = CGRect(x: 0, y: 50, width: 100, height: 30)
label.numberOfLines = 2
//label.text = "Hello"
label.textColor = UIColor.black
return label
}()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
contentView.addSubview(caseId)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
【问题讨论】:
-
问题是因为我在
awakeFromNib函数中添加子视图,我才知道awakeFromNib()不会被调用,除非有nib文件。 -
图中显示UITableView是入口点,但UItabbar控制器应该是。
标签: swift uitableview tableviewcell