在UITableView的动态单元格中Swift-Access UILabels [英] Swift-Access UILabels in dynamic cells in UITableView

查看:180
本文介绍了在UITableView的动态单元格中Swift-Access UILabels的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个原型单元格,并将其用作动态UITableView的模板:

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

如何访问单元格中的UIButtons和UILabels来设置每个单元格的内容和自定义Action?

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

推荐答案

首先,您需要使用您的插座来声明UITableViewCell的子类,并将其与原型相连接

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

然后,您的tableView(tableView:cellForRowAtIndexPath indexPath :)方法将如下所示:

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

通过覆盖tableView(tableView :,)为每个单元格添加一个自定义操作doSelectRowAtIndexPath indexPath :)方法UITableViewDelegate:

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

这篇关于在UITableView的动态单元格中Swift-Access UILabels的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆