How to access custom UITableViewCell from main ViewController

custom uitableviewcell swift programmatically
custom uitableviewcell programmatically
custom uitableviewcell storyboard
custom uitableviewcell swift 4 programmatically
custom tableview cell swift 4
custom cell (swift)
ios uitableview custom cell programmatically objective-c
uitableview with multiple custom cells tutorial

I have a main view controller with UITableView. Table view have 2 cells prototyped in IB.

Prototyped Cells

The first cell is in section 0 and the second cell is in section 1 (to be always at the bottom of the table).

Here is my table definition in main 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()
    }
}

All the Outlets to the cells are defined in custom UITableViewCell:

class ItemTableViewCell: UITableViewCell {

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

How can I access the values (read and change) of outlets variables in ItemTableViewCell from main ViewController?

For example, when "+" button pressed in the second cell, I need to TextView become the FirstResponder, and then save the value of TextFiled.

And also I need to edit the TextFields on the 0 section cells and then save data from them.

If you have only 2 no. of sections and one row in each section, then you can give addItemButton tag value equal to section number. Then add action to that button and define a corresponding selector. In that selector method, get the section value from sender's tag and get the indexpath corresponding to section and row(=0). From that indexpath, get the cell and then you can access any outlet of Cell in Main Controller.

Thanks

How to access custom UITableViewCell from main ViewController, If you have only 2 no. of sections and one row in each section, then you can give addItemButton tag value equal to section number. Then add  But my switch is in a UITableViewCell. I have no idea how to call delegate of viewcontroller from the UITableViewCell. I put a switch in a custom table cell. The cell is belong to a Table, and that table is in a View. The delegate is implemented in the view controller. The custom cell has its own class.

You want to

  1. Get button press events on the custom UITableViewCell
  2. Change IBOutlet values from the main UIViewController

Firstly to get button press events on the cell object, you have 2 options:

1.1 Attach a target when instantiating the cell:

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

1.2 Use a delegate structure: have the ItemTableViewCell declare a delegate protocol, capture button press events in this class via an IBAction outlet, and pass up the event using the delegate. The main ViewController conform to the protocol and implement the delegate callback.

Secondly - accessing the IBOutlets of the cell. Anywhere you need to access the cell:

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 

iOS custom Table Views with Cells - Q agency, Now go to the Main.storyboard, click on the “Library” on the top right corner, That being said, we can create a custom cell for our tableView. Now we can go back to our ViewController.swift and get the data we just created. I have a class called MAGradeCell that's a custom UITableViewCell class. Before I had the class and I was setting up the cell from inside the view controller (MAController), I just configureHeaderC

I've made it with the current cell defined as custom cell instance (it's a code to save data to CoreData when finished editing a TextView in a cell):

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 value I'm taking when starting editing the cell:

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

Creating Custom Table View Cells, In the previous section, we set up our table view controller to display some sample data. Before we create our custom cell, let's adjust the row height for each cell in In Main.storyboard , increase the table view's row height to the following: Next, we'll need to create a way to access the title and last modified labels on  A table view controller displays structured, repeatable information in a vertical list. You use the UITableViewController class in your iOS app to build a table view controller. Working with a table view controller also means working with a few important iOS development concepts, such as subclassing, the delegation design pattern, and re-using views.

Using Custom cells to customize UITableViewCells, Hint: In Xcode 11.3 Add New Constraints doesn't allow to enter a distance of 0 anymore. This seems to be a bug in Xcode. To get a margin of 0  iOS custom UITableViewCell example using xib file The UITableViewCell class defines the attributes and behavior of the cells that appear in UITableView objects. The iOS SDK comes with some predefined cell styles for your most common needs but what if you need a different layout for your table row data.

UITableViewController - iOS & Swift Tutorial, Using Custom cells to customize UITableViewCells Open Main.storyboard and drag in a new Table View Controller from the Object Library: have an optional imageView that is created when the property is accessed):. Access a property from the FirstViewController in a custom UITableViewCell Tag: ios , xcode , uitableview , properties , import In my iOS app I have a custom UITableViewCell that is part of a TableView in my FirstViewController .

Using UITableView, The sections below cover basic as well as more custom table views. Create a view controller, and drag a UITableView into the view, as shown below. Get the index path from the cell that was tapped let indexPath = tableView. Open the view controller's XIB file, delete the view controller's view, and drag a table view from the Object Library. Select the table view and set its dataSource and delegate outlets to the File's Owner, that is, the view controller. Select the File's Owner and set its view outlet to the table view (figure 11).

Comments