如何从主ViewController访问自定义UITableViewCell

时间:2018-06-05 06:03:46

标签: ios swift uitableview

我有一个带UITableView的主视图控制器。表视图在IB中有2个单元格原型。

Prototyped Cells

第一个单元格位于第0部分,第二个单元格位于第1部分(始终位于表格的底部)。

这是主ViewController中的表定义:

    func numberOfSections(in tableView: UITableView) -> Int {
    return 2
    }

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
    return itemNames.count
    } else {
    return 1
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

// Created additional section where will be the cell for adding items (always at bottom)
    switch indexPath.section {
    case 0:
    let cellIdentifier = "itemCell"
    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ItemTableViewCell

    cell.itemNameTextView.text = itemNames[indexPath.row]
    let currentImage = itemImages[indexPath.row]
    cell.itemStateButton.setImage(UIImage(named: currentImage), for: UIControlState.normal)

    return cell

    case 1:
    let cellIdentifier = "addItemCell"
    let addCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ItemTableViewCell

    addCell.addItemButton.setImage(UIImage(named: "plus-math-40"), for: UIControlState.normal)

    return addCell

    default:
    return UITableViewCell()
    }
}

单元格的所有Outlets都是在自定义UITableViewCell中定义的:

class ItemTableViewCell: UITableViewCell {

@IBOutlet var itemNameTextView: UITextView!
@IBOutlet var itemStateButton: UIButton!
@IBOutlet var addItemButton: UIButton!
@IBOutlet var addTextView: UITextView!

如何从主ViewController访问ItemTableViewCell中的outlet变量的值(读取和更改)?

例如,当" +"按下第二个单元格中的按钮,我需要将TextView变为FirstResponder,然后保存TextFiled的值。

此外,我还需要编辑0部分单元格上的TextFields,然后从中保存数据。

3 个答案:

答案 0 :(得分:0)

如果你只有2个没有。每个部分中的部分和一行,然后您可以将addItemButton标记值等于部分编号。然后向该按钮添加操作并定义相应的选择器。在该选择器方法中,从发送者的标记中获取节值,并获取与节和行(= 0)对应的索引路径。从该索引路径获取单元格,然后您可以访问主控制器中单元格的任何插座。

由于

答案 1 :(得分:0)

你想要

  1. 在自定义UITableViewCell
  2. 上获取按钮按下事件
  3. 从主UIViewController
  4. 更改IBOutlet值

    首先要在单元格对象上获取按钮事件,您有两个选择:

    1.1实例化单元格时附加目标:

    // In your tableView cellForRow method
    addCell.addItemButton.addTarget(self, action: #selector(bringUpTextfieldMethod), for: .touchUpInside)
    

    1.2使用委托结构:让ItemTableViewCell声明委托协议,通过IBAction出口捕获按钮按下此类中的事件,并使用委托传递事件。主ViewController符合协议并实现委托回调。

    其次 - 访问单元格的IBOutlets。您需要访问单元格的任何地方:

    let indexPath = IndexPath.init(row: 0, section: 0) // Obviously with the correct row/sec
    let itemCell = tableView.cellForRowAtIndexPath(indexPath) as! ItemTableViewCell  // your tableview must be an IBOutlet on your view controller
    
    // Now you can access properties on itemCell
    // e.g:
    let name = itemCell.itemNameTextView.text 
    

答案 2 :(得分:0)

我已将当前单元格定义为自定义单元格实例(它是在单元格中完成编辑TextView时将数据保存到CoreData的代码):

func textViewDidEndEditing(_ textView: UITextView) {

    currentTextView = nil

    // Finished edit tex tin text view. Save new values to CoreData
    let currentCell = tableView.cellForRow(at: currentIndexPath) as! ItemTableViewCell
    if let appDelegate = (UIApplication.shared.delegate as? AppDelegate) {

        // Add Mode. Adding values from addItemCell to CoreData
        if editMode == false {
            // In add mode we need to add a new record to CoreData
            // Check if textview is not empty
            if currentCell.addTextView.text != "" {
            shoppingItem = ItemMO(context: appDelegate.persistentContainer.viewContext)
            shoppingItem.itemName = currentCell.addTextView.text
            shoppingItem.itemCreatedDate = Date()
            shoppingItem.itemDone = false
            currentCell.addTextView.text = ""
            }
        } else {
            // In edit mode we need to save current values and save context
            if currentCell.itemNameTextView.text != "" {
            shoppingItems[currentIndexPath.row].itemName = currentCell.itemNameTextView.text
            }
            }
        appDelegate.saveContext()
        tableView.reloadData()
        }

    }

开始编辑单元格时我正在使用的currentIndexPath值:

func textViewDidBeginEditing(_ textView: UITextView) {

    currentTextView = textView

    var superview = textView.superview
    while let view = superview, !(view is UITableViewCell) {
        superview = view.superview
    }
    guard let cell = superview as? UITableViewCell else {
        //print("button is not contained in a table view cell")
        return
    }
    guard let indexPath = tableView.indexPath(for: cell) else {
        //print("failed to get index path for cell containing button")
        return
    }

    // Setup current index path value
    self.currentIndexPath = indexPath

    // Setup edit mode for data saving in textViewDidEndEditing
    if currentIndexPath.section == 0 {
        editMode = true
    } else {
        if currentIndexPath.section == 1 {
            editMode = false
        }
    }
}