gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:02:32 25 4
gpt4 key购买 nike

下面是我如何在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com