UILabels Swift-Access on dynamic cells in UITableView

I created a cell prototype and used it as a template for a dynamic UITableView: screenshot

How do I access the UIButtons and UILabels in a cell to set the content and custom action for each cell?

+3


source to share


2 answers


First you need to declare a subclass of UITableViewCell with your points and connect them to the prototype

class MyCustomCell: UITableViewCell {
    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var label3: UILabel!
}

      

Then your tableView (tableView: cellForRowAtIndexPath indexPath :) method will look like this:



func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cell id")

    if (cell == nil) {
        cell = MyCustomCell()
    }

    (cell as MyCustomCell).label1.text = "Some text"
    (cell as MyCustomCell).label2.text = "Some text"
    (cell as MyCustomCell).label3.text = "Some text"

    return cell;
}

      

Add a custom action for each cell, which you can by overriding the tableView (tableView :, didSelectRowAtIndexPath indexPath :) UITableViewDelegate method:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    switch(indexPath.row) {
    case 1:
        action1()
    case 2:
        action2()
        //and so on
    }
}

      

+2


source


In cellForRowAtIndexPath

get Button

and Label

using the tag(which can be specified in Storyboard

).

    // 1 is tag value, which is set for UILabel in Storyboard
    var label = tableCell.viewWithTag(1) as? UILabel
    label?.text = "Your Title"

    // 2 is tag value, which is set for UIButton in Storyboard
    var button = tableCell.viewWithTag(2) as? UIButton
    // Now Set Dynamic Tag
    button?.tag = indexPath.row
    button?.addTarget(self, action: "btnClicked:", forControlEvents: UIControlEvents.TouchUpInside)

      



and in yours Button Action

, depending on the value of the tag, do your action.

func expandButtonClicked(sender: UIButton) {
    var btnTag = sender.tag
    if(btnTag == 1) {
        // Action 1
    }
    else if(btnTag == 2) {
        // Action 2
    }
}

      

0


source







All Articles