Reputation: 35
I've recently started to learn iOS development and I ran into some problems.
I have a tableview with custom cell: Label, image view (hidden by default) and a button. I want it to work so that when the button is clicked for the cell the image view gets shown. The problem is that every time the cell is reused the image view is shown for the reused cell. I want to get it to work so that if the button is pressed for the first cell, ONLY the first cells image view is shown. If the button for first and third cell is pressed the image view should show ONLY for first and third row and not any other row.
My current solution:
class CustomTableViewCell: UITableViewCell {
@IBOutlet var cellTitleLabel: UILabel!
@IBOutlet var cellImageView: UIImageView!
var showImageView = false
@IBAction func showImageViewAction(sender: UIButton) {
showImageView = true
displayCell()
}
func displayCell() {
if showImageView {
cellImageView.hidden = false
} else {
cellImageView.hidden = true
}
}
}
And for the view controller:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 30
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomTableViewCell
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let customCell = cell as! CustomTableViewCell
customCell.displayCell()
}
Any suggestions on how to create so that the image view gets hidden when the cell is reused?
Upvotes: 3
Views: 1451
Reputation: 1222
if you have to save the cellImageview.hidden
status just do like so:
add protocol to inform the MainClass that the actionButton is pressed:
protocol customCellDelegate{
func actionButtonDidPressed(tag: Int, value: Bool)
}
than in your CustomTableViewCell declare
var delegate: customCellDelegate?
and in the @IBAction func showImageViewAction(sender: UIButton)
add:
@IBAction func showImageViewAction(sender: UIButton) {
cellImageView.hidden = ! cellImageView.hidden
delegate?.actionButtonDidPressed(self.tag, value: imageCell.hidden)
}
in your mainView make it conform to customCellDelegate
var status = [Bool]()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let rowCount = 100
for _ in 0 ..< rowCount{
status.append(true)
}
return rowCount
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! customcell
cell. cellImageView.hidden = true
cell. cellImageView.hidden = status[indexPath.row]
cell.delegate = self
cell.tag = indexPath.row
return cell
}
func actionButtonDidPressed(tag: Int, value: Bool) {
status[tag] = value
}
Upvotes: 1