Kobski
Kobski

Reputation: 1636

Custom UITableViewCell with drawRect + normal blue selection

I have a custom UITableViewCell. All the drawing is done in the drawRect: method and no subviews are added. The drawing works fine and the scroll speed is good. But the problem is with the selected cells. I want the selection to behave like it would normally:

I have not been able to achieve all three.

First attempt:
Set selectionStyle = UITableViewCellSelectionStyleNone and do the selection color in the drawRect method. With this method, I am able to achieve the first two things, but the deselection is instant. So one second it is selected blue, the next second it is deselected. I do not get the nice fade-out.

Second attempt:
selectionStyle = UITableViewCellSelectionStyleBlue With this method my cell is all gradient blue when selected. The text I have is not visible. The fade-out works nicely, though.

Third attempt:
Set selectionStyle = UITableViewCellSelectionStyleBlue and also set selectedBackgroundView to a UIView where I set the backgroundColor to a transparent blue. Here the problem is that the selectedBackgroundView (despite the name) is drawn on top of my normal content. So if the selectedBackgroundView is not transparent, I cannot see the text. And if it is transparent, I can see the text, but the selection color gets "faded" and does not look right.

What would be the correct way of achieving all three bullet points?

Upvotes: 1

Views: 4205

Answers (2)

Kobski
Kobski

Reputation: 1636

OK. So the answer to my own question... Don't subclass UITableViewCell for custom drawing. Instead subclass a UIImageView or a UIView.

This post has a nice description of how to do it:
http://cocoawithlove.com/2009/04/easy-custom-uitableview-drawing.html

Upvotes: 2

Joetjah
Joetjah

Reputation: 6132

I'd suggest using the second attempt in combination with a gesture recognizer. Check if the user presses on a cell, if so, set the textcolor in that cell to yellow (or what is the inversion of blue? xD).

Sample code:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if (touch.view isKindOfClass:[UIButton class]]) {
        //do something with that view, for example: 
        //change the color of the text in that view, 
        //or invert it ;)
        return YES;
    }
    return NO;
}

Alternatively, you can attach a UIGestureRecognizer to that button. That way, you get the class called inserted in the selector.

There might be a better option to do what you asked. This just came up my mind, if you have 2/3 points working already, this should help you to get 3/3.

Upvotes: 0

Related Questions