I have a UITableView
and I am trying to add some content ( Whish
) in my case. I have set up everything programmatically but somehow adding cells
is not working for me.
This is my UITableView
and custom Wish
Class for my data:
import UIKit
class WhishlistTableViewController: UITableViewController {
public var wishList : [Wish]?
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(WhishCell.self, forCellReuseIdentifier: WhishCell.reuseID)
self.wishList?.append(Wish(withWishName: "Test"))
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return wishList?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: WhishCell.reuseID, for: indexPath)
let currentWish = self.wishList![indexPath.row]
cell.textLabel?.text = currentWish.wishName
return cell
}
}
class Wish: NSObject {
public var wishName : String?
init(withWishName name: String) {
super.init()
wishName = name
}
}
And this is how I am creating the WishlistTableView
inside my other UIViewController
:
let theTableView: WhishlistTableViewController = {
let v = WhishlistTableViewController()
v.view.layer.masksToBounds = true
v.view.layer.borderColor = UIColor.white.cgColor
v.view.layer.borderWidth = 2.0
v.view.translatesAutoresizingMaskIntoConstraints = false
return v
}()
and its constraints
:
theTableView.view.topAnchor.constraint(equalTo: wishlistView.topAnchor, constant: 180.0),
theTableView.view.bottomAnchor.constraint(equalTo: wishlistView.bottomAnchor, constant: 0),
theTableView.view.leadingAnchor.constraint(equalTo: wishlistView.safeAreaLayoutGuide.leadingAnchor, constant: 30.0),
theTableView.view.trailingAnchor.constraint(equalTo: wishlistView.safeAreaLayoutGuide.trailingAnchor, constant: -30.0),
The TableView
appears just fine with its constraints
but adding cells
is not working and I have no idea why.. Grateful for every help :)
Replace
public var wishList : [Wish]?
with
public var wishList = [Wish]()
As you never init wishList
so adding item here wishList?.append
won't do anything
self.wishList.append(Wish(withWishName: "Test"))
Also remove this as it's the default
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.