简体   繁体   中英

Pass data to tableView cell swift

I have a Table with a cell in it. Within the Cell there is a Picker View

在此处输入图片说明

Now I want to pass data (an array of objects) from the Parent Controller to the Table View Cell so I can show the data in the Picker View

var foodServings:[FoodUnit]=[]
func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath)->UITableViewCell{
    let cell = tableView.dequeueReusableCellWithIdentifier("recipeIngredientCell",forIndexPath: indexPath) as! ReceiptIngredientsViewCell
    let row = indexPath.row
    cell.ingredientName.text = foods[row].name
    cell.ingredientText.text = foodQuantities[row]

  // cell.foodServings = self.foodServings

    return cell

}

I hoped I can send Data to the Cell but this didnt work.

I try to clearify it a bit:

Thats how the table is constructed

with:

 cell.ingredientName.text = foods[row].name
 cell.ingredientText.text = foodQuantities[row] 

I can access the cell Labels for example bean and the text in the textview

But to populate the picker view i need to send an array of data to each cell so that i can populate the picker view.

如果您只是传递数据,则可以使用全局变量/构造函数将值传递给单元格。

Please check these:

  • is the cell with "recipeIngredientCell" identifier is there in your storyboard?
  • is foods array is filled with your data?
  • is foodQuantities array is filled with your data?
  • have you implemented tableView(_:numberOfRowsInSection:) method? This method must return number of your rows, for example foods.count

First of all, you can check out this tutorial about UIPickerView

Did you connect the UIPickerViewDelegate and UIPickerViewDataSource to your viewController?

After that, make sure you have implemented those delegate methods:

 // The number of rows of data
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return foodServings.count
}

 // The data to return for the row and component (column) that's being passed in
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return foodServings[row]
}

// Catpure the picker view selection
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    // This method is triggered whenever the user makes a change to the picker selection.
    // You can update your cell's UI here. For example:
    let indexpath = NSIndexPath(row: , section:)
    let cell = self.tableView(tableView, cellForRowAt: indexPath)      
    cell.yourTextField.text = foodServings[row]
}

From what you have provided us, I can only tell that your foodServings array is empty, so could you please show me all the codes in this class?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM