问题描述
我在我的表视图控制器类中收到此错误消息
uitableviewcell 的值没有成员委托
import UIKit
class TViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var Tviews: UITableViewCell!
let contacts:[[String]] = [
["Elon Musk","+1-201-3141-5926"],["Bill Gates","+1-202-5358-9793"],["Tim Cook","+1-203-2384-6264"],["Richard Branson","+1-204-3383-2795"],["Jeff Bezos","+1-205-0288-4197"],["Warren Buffet","+1-206-1693-9937"],["The Zuck","+1-207-5105-8209"],["Carlos Slim","+1-208-7494-4592"],]
override func viewDidLoad() {
super.viewDidLoad()
Tviews.delegate = self
Tviews.datasource = self
// Do any additional setup after loading the view.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return contacts.count
}
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableViews",for: indexPath)
print("\(#function) --- section = \(indexPath.section),row = \(indexPath.row)")
cell.textLabel?.text = contacts[indexPath.row][0]
return cell
}
解决方法
您应该将委托和数据源分配给您的表格视图实例,而不是您的表格视图单元格。
为了做到这一点,在 TViewController 文件中创建一个带有 table view 的 outlet 链接,然后像这样编辑你的代码:
import UIKit
class TViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
let contacts:[[String]] = [
["Elon Musk","+1-201-3141-5926"],["Bill Gates","+1-202-5358-9793"],["Tim Cook","+1-203-2384-6264"],["Richard Branson","+1-204-3383-2795"],["Jeff Bezos","+1-205-0288-4197"],["Warren Buffet","+1-206-1693-9937"],["The Zuck","+1-207-5105-8209"],["Carlos Slim","+1-208-7494-4592"],]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.datasource = self
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return contacts.count
}
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "<your-table-view-cell-id>",for: indexPath) as! YourTableViewCell
cell.textLabel?.text = contacts[indexPath.row][0]
return cell
}
}