Arefly Arefly - 7 months ago 12
Swift Question

Pass variable to custom UITableViewCell from UIViewController

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
}


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


It returns
result: nil nil


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


So how can I pass data to RunningTableViewCell?

Answer

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
}