我有問題,我的TableViewController不顯示單元格的內容。我有一個加載數據的按鈕,但它也應該顯示在單元格中。我在「vieDidLoad」功能中忘記了什麼嗎?您可以從故事板和應用程序的最後找到圖像。Swift TableView單元格不顯示
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "TableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "TableViewCell")
}
override func viewWillAppear(_ animated: Bool) {
let btn = UIButton(frame: CGRect(x: 0, y: 25, width: self.view.frame.width, height: 50))
btn.backgroundColor = UIColor.cyan
//btn.setTitle("Add new Dummy", for: UIControlState)
btn.addTarget(self, action: #selector(addDummyData), for: UIControlEvents.touchUpInside)
self.view.addSubview(btn)
}
@objc func addDummyData() {
RestApiManager.sharedInstance.getRandomCar { (json: NSArray?) in
if let results = json {
for entry in results {
self.items.append(CarObject(json: entry as! Dictionary))
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
func tableView(tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "TableViewCell") as! TableViewCell
}
let car = self.items[indexPath.row]
print(car.pictureURL)
if let url = NSURL(string: car.pictureURL) {
if let data = NSData(contentsOf: url as URL) {
cell.carImage?.image = UIImage(data: data as Data)
}
}
// Create Swift/Cocoa Touch file with carImage etc. Actionbutton
cell.carTitleLabel.text = "test"//car1
cell.carPriceLabel.text = car.carPrice
print("test3")
return cell
}
}
您是否添加了numberOfRowsInSection委託? –
可能重複[TableView不重新加載](https://stackoverflow.com/questions/16681525/tableview-not-reloading) – Yuyutsu
我試過這些:func numberOfSectionsInTableView(tableView:UITableView) - > Int { return 1 } func tableView(tableView:UITableView,numberOfRowsInSection section:Int) - > Int { return self.items.count; } – Skrai2004