Rouslan Karimov
Rouslan Karimov

Reputation: 585

UIPickerView + TableViewCell + delegates and datasource

I have Table view Controller and separate class which handles for me tableviewcell. Inside the tableview cell I have pickerview. How to implement delegate and datasource for pickerview which is in tableCell class but my delegate functions in tableview controller?

Upvotes: 1

Views: 1861

Answers (2)

Maklaus
Maklaus

Reputation: 688

For Swift:

  1. Create outlet for UIPickerView in custom table view class:

    class MyTableViewCell: UITableViewCell, UIPickerViewDelegate, UIPickerViewDataSource {
        @IBOutlet var myPickerView: UIPickerView!
    }
    
  2. Add delegate and datasource in "cellForRowAtIndexPath" in ViewController:

    class myViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITableViewDelegate, UITableViewDataSource {
        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {            
            let cell = tableView.dequeueReusableCellWithIdentifier("myCell") as! MyTableViewCell
    
            cell.myPickerView.dataSource = self
            cell.myPickerView.delegate = self
    
            return cell
        }
    }
    

Upvotes: 2

geekydevjoe
geekydevjoe

Reputation: 108

You could have your tableView controller set a property on the tableview cells as they are created indicating that it is the delegate and datasource.

On the tableviewcell class you created just add a property that is an instance of you tableview controller. Like

@property (nonatomic, retain) MyTableViewController * pickerDelegate;

Then in your cellForRowAtIndexPath you can set that property to self

cell.pickerDelegate = self;

You might need to also set some sort extra property like a tag to distinguish between each cell. I would think another property on the tableviewcell like an NSIndexPath would do.

Upvotes: 1

Related Questions