ios - 将变量从 UIViewController 传递到自定义 UITableViewCell

标签 ios swift uiviewcontroller uitableview

下面是我如何在 UIViewController 中使用自定义 UITableViewCell RunningTableViewCell:

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

返回result: nil nil

结果的用法是:(SomeButtonRunningTableViewCell里面的子view)

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

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

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

最佳答案

awakeFromNib 在 View 及其 subview 分配和初始化后立即调用。

所以在委托(delegate)方法func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 。这就是为什么 isTopisBottomawakeFromNib 中是 nil 的原因。

您可以在 RunningTableViewCell 中定义方法,该方法将使用此变量加载单元格。

func load(isTop: Bool, isBottom: Bool) {
    self.isTop = isTop
    self.isBottom = isBottom

    // Update cell UI as you wish
}

最后在 View Controller 中重写委托(delegate)方法 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

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

    let isTop = indexPath.row == 0
    let isBottom = indexPath.row == myArray.count-1

    cell.load(isTop, isBottom: isBottom)

    return cell
}

关于ios - 将变量从 UIViewController 传递到自定义 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35957199/

相关文章:

iphone - 从 iPhone 的地址簿中选择一个联系人并在其中添加一个新的电话号码

ios - 如何在后台运行 NSTimer 超过 180 秒?

ios - 我的测试目标中没有这样的模块 'XXX'

ios - 为什么 shouldPerformSegue 使用字符串,我该如何使用 UIStoryboardSegue 来代替它?

ios - 在两个 UiViewController 和 UIView 之间实现拖动和滑动过渡?

ios - 当应用程序在 iOS Swift 中仅支持纵向方向时,如何在我的 SDK VideoViewController 中强制旋转到横向方向

ios - UIRefreshControl 与两个异步 json 下载来填充 UITableView 行和自定义标题 View

ios - 协议(protocol)方法不起作用

swift - 单击静态表格单元格时可以从服务器获取数据吗?

iphone - 使用一个 ViewController 处理多个场景