ios - tableview 自定义单元格注册失败
问题描述
我正在尝试为我的表格视图使用自定义单元格,我创建了新的 TableViewCell 并将单元格命名为“单元格”
在具有 tablView 的 viewController 中,我注册了单元格
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
self.tableView.register(TableViewCell.self, forCellReuseIdentifier: "Cell")
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
cell.cellTitle?.text = ads[indexPath.row].title
let imageName = ads[indexPath.row].document
let image = UIImage(named: imageName)
cell.imgView?.image = image
return cell
}
但是当我运行应用程序时,它会显示 tableView 中的默认单元格而不是自定义单元格?请有任何建议
具有表格视图的整个 ViewContoller 代码
import UIKit
import Foundation
import Alamofire
import SwiftyJSON
final class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var ads = [photo]()
@IBOutlet private weak var tableView: UITableView!
override func viewDidLoad() {
self.tableView.register(TableViewCell.self, forCellReuseIdentifier: "Cell")
super.viewDidLoad()
downloadJson {
self.tableView.reloadData()
}
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ads.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
cell.cellTitle?.text = ads[indexPath.row].title
let imageName = ads[indexPath.row].document
let image = UIImage(named: imageName)
cell.imgView?.image = image
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "SecondPageSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? SecondView {
destination.Ads = ads[(tableView.indexPathForSelectedRow?.row)!]
}
}
func downloadJson(completed: @escaping () ->()) {
let url = URL(string: "https://mysite.co/apis/all.php")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.ads = try JSONDecoder().decode([photo].self, from: data!)
DispatchQueue.main.async {
completed()
}
} catch {
print("JSON ERROR")
}
}
}.resume()
}
}
表格视图和自定义 TableViewCell
这是有关其工作原理的视频 rn:https ://imgur.com/vZEOBTm
解决方案
这条线
self.tableView.register(TableViewCell.self, forCellReuseIdentifier: "Cell")
需要从该方法中移出,并在呈现表视图之前执行。viewDidLoad()
将它移动到的好地方。
推荐阅读
- swift5 - 如何在 iOS(swift 5)应用程序中集成 Touch ID 和 Face ID
- python - python如何绕过我之前的代码先运行后面的代码?
- sql - 消除与 SQL Server 中原始表交换后变得相同的行
- c# - 使用 .net core Entity Framework 从 JSON 创建嵌套数据
- xslt - XSLT 副本不包括属性
- java - 严重:无法将数据库状态与会话同步
- c# - 来自对 webform localhost 中 webmethods 的 AJAX 调用的未知 web 方法错误
- r - 当前一个值不是 1 时,用前一个值代替当前值,直到在 R 中找到下一个非 1 值
- c# - 如何在运行时使用 MenuItems 动态填充 MenuItem?
- python - 使用 uproot 继续读取压缩问题的树数据