I have a Custom Tableview
cell in swift and in that cell a label.
I want to be able to change the label when you select a cell.
How can I reference my custom UITableviewCell
label in didSelectRowAtIndexPath
In Objective C to reference my custom cell in didSelectRowAtIndexPath
I would use the following:
MPSurveyTableViewCell *cell = (MPSurveyTableViewCell *)[tableViewcellForRowAtIndexPath:indexPath];
cell.customLabel.TextColor = [UIColor redColor];
What must I do in swift to achieve the same result?
The Above Answers Are Incomplete
Because a UITableView reuses cells you need to check if the cells are selected and adjust the color appropriately in cellForRowAtIndexPath. There may be typos, but this is the complete answer:
func tableView(tableView: UICollectionView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifierHere", forIndexPath: indexPath) as! MPSurveyTableViewCell
// setup your cell normally
// then adjust the color for cells since they will be reused
if cell.selected {
cell.customLabel.textColor = UIColor.redColor()
} else {
// change color back to whatever it was
cell.customLabel.textColor = UIColor.blackColor()
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
let cell = tableView.cellForRowAtIndexPath(indexPath) as! MPSurveyTableViewCell
cell.customLabel.textColor = UIColor.redColor()
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
}
func tableView(tableView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath) as! MPSurveyTableViewCell
// change color back to whatever it was
cell.customLabel.textColor = UIColor.blackColor()
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
}
why not use setSelected in UITableViewCell subclass?
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
customLabel.textColor = selected ? UIColor.red : UIColor.black
}
or if you want it to go back to deselected color after a specific amount of time:
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
customLabel.textColor = UIColor.red
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2, execute: { [weak self] in
self?.customLabel.textColor = UIColor.black
}
}
}
Then just set your cell selectionStyle = .none
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With