Please can somebody help me. I spent about 1 week, trying to resolve it by myself. I got tableview and MVC paradigm. I can't setup cellForRow and numbersOfSections. Because it like extension in UIView, but I can't save any properties in UIView due to MVC paradigm. Can somebody explain me how I can resolve this problem?
class ShopView: UIView {
private(set) lazy var productListTableView: UITableView = {
let productList = UITableView()
productList.dataSource = self
productList.translatesAutoresizingMaskIntoConstraints = false
return productList
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.setupLayout()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupLayout()
}
}
class ShopViewControllerModel: UIViewController {
weak var coordinator: MainCoordinator?
let requestFactory = RequestFactory()
private var shopTableView: ShopView {
return self.view as! ShopView
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
override func loadView() {
super.loadView()
self.view = ShopView()
}
}
extension ShopViewControllerModel {
{
func download(completion: @escaping (Product) -> ()) {
let getGoods = requestFactory.getGoods()
getGoods.getNewGoods(pageNumber: 1, id_category: 1) { response in
switch response.result {
case .success(let goods):
for index in goods.products {
let array = Product(product_name: index.product_name, id: index.id, price: index.price)
completion(array)
}
case .failure(let error):
print(error.localizedDescription)
}
}
}
}
class ShopViewController: UIViewController {
lazy var shopTableView = ShopViewControllerModel()
weak var coordinator: MainCoordinator?
var totalGoodsModel: [Product] = []
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Shop"
self.navigationController?.navigationBar.isHidden = true
self.view.backgroundColor = .red
addEditVC()
}
private func addEditVC() {
self.shopTableView.download { (response) in
self.totalGoodsModel = [response]
print(self.totalGoodsModel)
}
}
extension ShopView: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sections = 2
return sections
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
self.productListTableView.register(UITableViewCell.self, forCellReuseIdentifier: "contactCell")
let cell = tableView.dequeueReusableCell(withIdentifier: "contactCell", for: indexPath) as! ShopTableViewCell
cell.textLabel?.text = "ShopTableViewCell"
return cell
}
}
ShopViewand move theproductListproperty to theShopViewControllerclass (also extension code) then if we assume thatShopViewControllerModelis the Model class of MVC then rename it toShopViewModeland make it not inherit fromUIViewController(and remove irrelevant functions). Then you have a good MVC design that most of us are very familiar with.