gpt4 book ai didi

ios - UITableViewCell类中的dequeueReuseableCellwithIdentifier方法如何使用?

转载 作者:行者123 更新时间:2023-11-28 08:39:26 25 4
gpt4 key购买 nike

通常,我们在 ViewController 类中使用 dequeueReuseableCellwithIdentifier 方法,但我想在 UITableViewCell 中使用此方法。我已经尝试过,但我得到了这样的异常。

fatal error: unexpectedly found nil while unwrapping an optional value  

View Controller 类:

@IBOutlet var tableView: UITableView!
var tableData:[songData] = [songData]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.backgroundColor = UIColor.orangeColor()

}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = TableViewCell()
cell.datas()
return cell
}

TableViewCell 类:

@IBOutlet var text1: UILabel!
@IBOutlet var text2: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func datas(){
let vc = ViewController()
let tableData = vc.tableData
print(tableData)
let tableview = vc.tableView
let indexpath:NSIndexPath = NSIndexPath()
let cell = tableview.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexpath) as! TableViewCell //The fatal error is showing exactly at this line.
let artistAndAlbum = tableData[indexpath.row]

cell.text1.text = artistAndAlbum.country
cell.text2.text = artistAndAlbum.currency
tableview.reloadData()
}

我需要在 TableViewCell 类中自定义我的表格数据。如果可以帮助我,否则为什么不能?

最佳答案

你的做法是错误的。老实说,创建​​自己的表格单元格子类没有任何意义。但是,让您的单元格子类传递数据并从中填充自身确实有意义。

您应该让您的 View Controller 像往常一样使单元格出队,然后更改您的表格单元格函数以将一些数据作为参数并自行更新。

在你的 View Controller 中:

override func viewDidLoad() {
super.viewDidLoad()

tableView.registerNib(UINib(nibName: "INSERT_NIB_NAME", bundle: nil), forCellReuseIdentifier: "Cell")
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
cell.updateWithData(tableData[indexPath.row])
return cell
}

如果您的单元格是 Storyboard中的原型(prototype)单元格,那么您必须在那里设置重用标识符,而不是在 viewDidLoad 中注册。

在您的表格单元格中:

func updateWithData(artistAndAlbum: songData) {
text1.text = artistAndAlbum.country
text2.text = artistAndAlbum.currency
}

关于ios - UITableViewCell类中的dequeueReuseableCellwithIdentifier方法如何使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36771665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com