1
試圖從一個類生成一個簡單的tableview。如果我將單元格設置爲「A」,它將在所有單元格中打印A,但對於當前的代碼輸出,它只顯示一個空白表格。我究竟做錯了什麼?對不起在這裏自學新手。tableview單元格不顯示類的文本
import UIKit
class LinesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var linesTableView: UITableView!
let cellID = "cell"
let lines = ["brown","red","blue"]
class Train {
var color: String = ""
var line: String = ""
init (color:String?, line:String?){
}
}
let brownLine = Train(color: "brown", line: "Brown Line")
let redLine = Train(color: "red", line: "Red Line")
let blueLine = Train(color: "blue", line: "Blue Line")
var trains: [Train] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
linesTableView.delegate = self
linesTableView.dataSource = self
trains = [brownLine,redLine,blueLine]
//print (trains[1].line)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lines.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = linesTableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)
let train = trains[indexPath.row]
cell.textLabel?.text = train.line
return cell
}
你忘了在'Train'初始化器中賦值,所以它們仍然是空字符串。 –
你有沒有嘗試把一個固定的文本先測試視覺?改變這個:cell.textLabel?.text = train.line for this:cell.textLabel?.text =「Hello」你還沒有正確地初始化你的類。 –