I created a prototype cell and use it as template for dynamic UITableView:
How do I access the UIButtons and UILabels in the cell to set the content and custom Action for each cell?
I created a prototype cell and use it as template for dynamic UITableView:
How do I access the UIButtons and UILabels in the cell to set the content and custom Action for each cell?
First you need to declare subclass of UITableViewCell with your outlets and connect them with your 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 you can by overriding tableView(tableView:, didSelectRowAtIndexPath indexPath:) method of UITableViewDelegate:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch(indexPath.row) {
case 1:
action1()
case 2:
action2()
//and so on
}
}
In your cellForRowAtIndexPath
get the Button
and Label
using tag (Which can be given 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 your Button Action
depending on tag value, do your action.
func expandButtonClicked(sender: UIButton) {
var btnTag = sender.tag
if(btnTag == 1) {
// Action 1
}
else if(btnTag == 2) {
// Action 2
}
}