Spring
Spring

Reputation: 11855

How to get cell selection on touchdown?

I have a custom tablecell and trying to show a different icon when it's selected. The problem is icon changes only after touchup and not right after touchdown (unlike selection background image). Is there a way to change this behaviour?

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    let cell = self
    if (selected) {
         cell.imageView?.image = UIImage(named: (selectedIconName!))

    } else {
         cell.imageView?.image = UIImage(named: (iconName!))

    }

Upvotes: 0

Views: 101

Answers (3)

redent84
redent84

Reputation: 19239

You can use setHighlighted instead of setSelected for that:

override func setHighlighted(highlighted: Bool, animated: Bool) {
    super. setHighlighted(highlighted, animated: animated)

    let cell = self
    if (highlighted) {
         cell.imageView?.image = UIImage(named: (selectedIconName!))

    } else {
         cell.imageView?.image = UIImage(named: (iconName!))

    }
}

Upvotes: 2

Sean Lintern
Sean Lintern

Reputation: 3141

You would be better off having a small model, array[NSIndexpath] then on didSelectRow: add the indexPath to the array and reconfigure the cell, passing in the selected state.

on didSelectRow:

if selectedPaths.contains(indexPath) {
    let i = selectedPaths.indexOf(indexPath)
    selectedPaths.removeAtIndex(i)
} else {
    selectedPaths.append(indexPath)
}

configCell(indexPath)

In your cellForRow: you can configure the cell with:

 cell.configure(selected: selectedPaths.contains(indexPath))

Upvotes: 0

Alexander Doloz
Alexander Doloz

Reputation: 4198

Override touchesBegan in your custom cell subclass:

class Cell: UITableViewCell {
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)
        // handle touch down
    }
}

Upvotes: 1

Related Questions