Swift-Access UILabels in dynamic cells in UITableView

与世无争的帅哥 提交于 2019-12-10 09:21:07

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/27738531/swift-access-uilabels-in-dynamic-cells-in-uitableview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!