从UIViewController将变量传递给自定义UITableViewCell [英] Pass variable to custom UITableViewCell from UIViewController

查看:171
本文介绍了从UIViewController将变量传递给自定义UITableViewCell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我如何在 UIViewController内使用我的自定义UITableViewCell RunningTableViewCell

Here is how I use my custom UITableViewCell RunningTableViewCell inside UIViewController:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! RunningTableViewCell

    //.......

    cell.isTop = false
    if(indexPath.row == 0){
        cell.isTop = true
    }

    cell.isBottom = false
    if(indexPath.row == myArray.count-1){
        cell.isBottom = true
    }

    return cell
}

此处是我的 RunningTableViewCell 类:( Cell的GUI在故事板内制作)

And here is my RunningTableViewCell class: (Cell's GUI is made inside storyboard)

class RunningTableViewCell: UITableViewCell {

    //@IBOutlet ...
    @IBOutlet weak var myButton: SomeButton!

    var isTop: Bool?
    var isBottom: Bool?

    override func awakeFromNib() {
        super.awakeFromNib()

        print("result: \(self.isTop) \(self.isBottom)")

        myButton.isTop = self.isTop
        myButton.isBottom = self.isBottom
    }
}

返回结果:nil nil

结果的用法是:( SomeButton RunningTableViewCell 内的子视图)

The usage of the result is: (SomeButton is a subview inside RunningTableViewCell)

class SomeButton: UIButton {
    var isTop = false
    var isBottom = false

    override func drawRect(rect: CGRect) {
        if(isTop){
            // DO SOMETHING...
        }
        if(isBottom){
            // DO SOMETHING...
        }
    }
}

那么如何将数据传递给RunningTableViewCell?

So how can I pass data to RunningTableViewCell?

推荐答案

你需要在ce中覆盖 prepareForReuse 二。并从 tableView:indexPath:中删除​​它。因此,当您滚动时,将重复使用单元格,但 isBotton isTop 将重置vars。

You need to override prepareForReuse in the cell. And remove it from tableView:indexPath:. So when you scroll the cell is going to be reused but the isBotton and isTop vars will be reseted.

override func prepareForReuse() {
    self.isBottom = false
    self.isTop = false
}

这篇关于从UIViewController将变量传递给自定义UITableViewCell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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