0

my problem is quite simple.. All I want is to set up a UITableView programmatically without the Storyboard.

I created my TableView and that works fine.. The problem is the UITableViewCell. It should only contain a UILabel but I don't get how to initialize it inside the class. And all the tutorials I have watched about UITableViews are done within Storyboard .. At least the set-up.

I am new to this and I know this is probably super easy but I couldn't find a solution for my problem. I am grateful for every help!

    import UIKit

class WhishCell: UITableViewCell {

    var whishText: String

    init(whishText: String){
        self.whishText = whishText
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

UPDATE

This is how i set up my UITableView inside my 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 then I also activate it like the rest of the items inside my UIViewController:

// constrain tableView
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 is inside a UIView which I let appear if the user taps on a button:

cell.wishlistTapCallback = {
        // let wishlistView appear
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: {
            self.wishlistView.transform = CGAffineTransform(translationX: 0, y: 0)
        })}
  • `let cell = tableView.dequeueReusableCell(withIdentifier: "whishCell") as! WhishCell` –  Nov 21 '19 at 23:41
  • sorry what do you mean by that? I didn't do anything in Storyboard –  Nov 21 '19 at 23:43
  • 1
    https://stackoverflow.com/questions/25413239/custom-uitableviewcell-programmatically-using-swift – Shehata Gamal Nov 21 '19 at 23:49
  • @Sh_Khan got that. Now it says I need to initialize `self.whishText` in `super.init`. But how do I do that? –  Nov 21 '19 at 23:57
  • You need to seperate your model from your views. The cell should not have properties for the data it presents. Use a model that is used to provide data to the cell. The cell can have a UILabel called wishTextLabel, if that is necessary, but not the string instance itself. See my example below. – pnizzle Nov 22 '19 at 01:44

1 Answers1

0

You are doing one thing very wrong there. You are setting your data directly on the cell (that var called whishText). Think about it, the name of a wish belongs to a wish, not to a cell. A name of a person belongs to a person, not to a cell. The cell just presents/shows the name of whatever object it is given. With that in mind. You need to have a class called Wish, and implement the UITableView Data source methods. Here is the code:

Wish Cell:

class WhishCell: UITableViewCell {

    public static let reuseID = "WhishCell"

    required init?(coder: NSCoder) {fatalError("init(coder:) has not been implemented")}

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = .systemTeal
        //other common things,
    }
}

WishTableViewController:

class WishTableViewController: UITableViewController {

    public var wishList : [Wish]?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.register(WhishCell.self, forCellReuseIdentifier: WhishCell.reuseID)
    }

    // 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
    }

}

Wish Model:

class Wish: NSObject {
    public var wishName : String?
    init(withWishName name: String) {
        super.init()
        wishName = name
    }
}

Usage Example:

@IBAction func showExampleWishTable(_ sender: Any) {
    let wishTableView = WishTableViewController()

    let wish1 = Wish(withWishName: "Bicycle")
    let wish2 = Wish(withWishName: "Macbook")
    let wish3 = Wish(withWishName: "Printer")

    wishTableView.wishList = [wish1, wish2, wish3]

    self.navigationController?.pushViewController(wishTableView, animated: true)
}

Result:

enter image description here

pnizzle
  • 6,243
  • 4
  • 52
  • 81
  • somehow this is not working for me. I implemented you exact code. The only thing I have different is that my `TableView` is already inside my `UIViewController` and I just let it appear/disappear with `. transofrm` . –  Nov 22 '19 at 13:46
  • @DieGlueckswurst `.transform?` You will need to post the relevant bits of your code. Especially the tableview code, and how you are creating and invoking the presentation of your tabview. You are definitely doing something wrong that you think is correct :) I can only tell once you put more code. – pnizzle Nov 22 '19 at 13:52
  • sure, I just updated my question :) sorry, `transform` is actually irrelevant. I just use it to change the `y-position` so I can let the view appear and disappear. But you can ignore that –  Nov 22 '19 at 14:22
  • @DieGlueckswurst I need to see where your data is coming from / how you are passing it to the tableview. Also post the code for `WhishlistTableViewController` – pnizzle Nov 22 '19 at 15:16
  • `WhishTableViewController` is your exact code + I also have the `class Whish` in that file. The only thing different is that I don't have a `func showExampleViewTable` but instead I copied what's inside that `function` and put it in `ViewDidLoad()` inside my `UIViewController` –  Nov 22 '19 at 15:24
  • I can send you my git but it's super messy :D –  Nov 22 '19 at 17:21
  • @DieGlueckswurst I've started a chat with you. – pnizzle Nov 24 '19 at 22:30
  • I don't see anything :/ –  Nov 24 '19 at 22:33
  • Let me start again – pnizzle Nov 24 '19 at 22:33