下面是我如何在 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
结果的用法是:(SomeButton
是RunningTableViewCell
里面的子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
。这就是为什么 isTop
和 isBottom
在 awakeFromNib
中是 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/