快速访问UITableView中的dynamic单元格中的UILabel
我创build了一个原型单元格,并将其用作dynamicUITableView的模板:
如何访问单元格中的UIButton和UILabel以设置每个单元格的内容和自定义操作?
首先,你需要用你的sockets声明UITableViewCell的子类,并将它们与你的原型连接起来
class MyCustomCell: UITableViewCell { @IBOutlet weak var label1: UILabel! @IBOutlet weak var label2: UILabel! @IBOutlet weak var label3: UILabel! }
然后你的tableView(tableView:cellForRowAtIndexPath indexPath :)方法将如下所示:
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; }
通过覆盖UITableViewDelegate的tableView(tableView:,didSelectRowAtIndexPath indexPath :)方法,为每个单元格添加一个自定义操作:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch(indexPath.row) { case 1: action1() case 2: action2() //and so on } }
在你的cellForRowAtIndexPath
获取Button
和Label
使用标签 (可以在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)
并根据标记值在Button Action
执行您的操作。
func expandButtonClicked(sender: UIButton) { var btnTag = sender.tag if(btnTag == 1) { // Action 1 } else if(btnTag == 2) { // Action 2 } }