Carl
Carl

Reputation: 783

Set animated UITableViewCell highlight color in Swift

By default the highlight effect of a UITableViewCell looks like this:

Default highlight effect

I'm looking for a similar effect that instead of grey is a custom color (for sake of example the UIColor default red value). I've tried to implement this myself using the setHighlighted delegate but it doesn't produce the animated effect the default style does.

This is the code I have used and the undesired effect that is achieved:

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

  if highlighted {
    self.backgroundColor = .red
  }
}

Alongside setting cell.selectionStyle = .none in cellForRowAt.

Undesired highlight effect

Is there any way to produce a native-like animated custom highlight color?

Upvotes: 0

Views: 827

Answers (2)

Ahmed AbdAlfattah
Ahmed AbdAlfattah

Reputation: 73

(Edited) You could use gestures to simulate the behaviour of the native, something like this:

  let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:")
yourCell.view.addGestureRecognizer(longPressRecognizer)

  func longPressed(sender: UILongPressGestureRecognizer)
   {
        if sender.state == .began {
            yourCell.animate(withDuration: 0.2, delay:0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEeaseOut, animations: { yourCell.backgroundColor = .red })

        }
        if sender.state == .ended {
            yourCell.animate(withDuration: 0.2, delay:0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEeaseOut, animations: { yourCell.backgroundColor = .white })
        }
   }

Upvotes: 0

Mina Gerges
Mina Gerges

Reputation: 329

You need to add another condition "else" for your "if" condition and clear the red background color to normal.

  if highlighted {
    self.backgroundColor = .red
  }else { 
    self.backgroundColor = .white
  }

Upvotes: 1

Related Questions