GJZ
GJZ

Reputation: 2542

Creating a Cocoa file

I created a Cocoa file with a subclass of UITableViewCell so I could have an outlet to a prototype cell. Would this work?

Upvotes: 0

Views: 68

Answers (2)

BevTheDev
BevTheDev

Reputation: 583

Create an array with the titles for all your labels. For instance:

var titleLabels: [String] = ["Eggs", "Cheese", "Milk"]

Load your custom cell class (put this in viewDidLoad):

var nib = UINib(nibName: "YourCellSubclass", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "cell")

Then implement cellForRowAtIndexPath:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

        cell.detailLabel?.text = self.titleLabels[indexPath.row]

        return cell
    }

(Make sure you remember to set this class as the datasource for your tableview).

To include the quantities on the cells, you'll need another array of numbers (or better yet, an array of objects, each with a name and quantity attribute). Then (assuming your cell has two labels - one for the title, one for the quantity) you can set both the titleLabel and quantityLabel on your cell in the same manner as shown above.

This article has a pretty good walkthrough on creating custom tableview cells: https://www.weheartswift.com/swifting-around/

Upvotes: 1

Charles
Charles

Reputation: 4528

You could create the custom UITableViewCell with two UILabels, for example titleLabel and detailLabel. In the custom initWithStyle method, you can set the desired position of the labels within the cell.

After initializing the custom cell, you could write another method in the custom UITableViewCell class that sets the text values of titleLabel and detailLabel, and call that method from cellForRowAtIndexPath. The desired values could come from an NSArray, and you would use the cell row, indexPath.row, to fetch the corresponding values from the array.

Upvotes: 1

Related Questions