Liran Revivo
Liran Revivo

Reputation: 1143

Add a UITableView to a view controller swift

I don't understand what am I doing wrong, I am trying to make an add button on the navigation bar so when you click it a little table view will be open in the page bottom and the user would be able to choose what to add (photo, video, and so on..) I connected the tableView with my cocoa touch class, as you can see it here:

class addTable: UITableView {

    let addObjects = ["Add Photo","Add Video","Add Link", "Add Sound Record", "Add Sound Track"]

    override func cellForRowAtIndexPath(indexPath: NSIndexPath!) -> UITableViewCell! {
        var cell:UITableViewCell = dequeueReusableCellWithIdentifier("addItem", forIndexPath: indexPath) as UITableViewCell
        
        cell.textLabel.text = addObjects[indexPath.row]
        return cell
    }

    override func numberOfRowsInSection(section: Int) -> Int {
        return addObjects.count
    }
    
    override func numberOfSections() -> Int {
        return 1
    }
}

I really don't understand why doesn't it work, the number of rows in the table is not even equals to the addObjects.count

I really hope you understand my question, Thank you guys!!

Upvotes: 1

Views: 4674

Answers (1)

Paulw11
Paulw11

Reputation: 114783

You have subclassed UITableView, but this is probably not necessary.

What you want is for this class to be the dataSource for a standard table view.

class addTable : NSObject, UITableViewDataSource{

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

        cell.textLabel.text = addObjects[indexPath.row]
        return cell
    }

    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return addObjects.count
    }


    func  numberOfSectionsInTableView(tableView: UITableView!) -> Int {
        return 1
    }

}

Then, in your view controller you can set an instance of this class as your tableview's data source -

self.myTableView.dataSource=addTable();

How you allocate and initialise the actual tableview is up to you - storyboard or through code, but it can just be a straight tableview.

Upvotes: 2

Related Questions