开发者

UIPickerView + TableViewCell + delegates and datasource

开发者 https://www.devze.com 2023-01-30 08:28 出处:网络
I have Table view Controller and separate class which handles for metableviewcell. Inside the tableview cell I h开发者_运维百科ave pickerview.

I have Table view Controller and separate class which handles for me tableviewcell. Inside the tableview cell I h开发者_运维百科ave pickerview. How to implement delegate and datasource for pickerview which is in tableCell class but my delegate functions in tableview controller?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消