tom
tom

Reputation: 14513

How to simulate the UITableviewCell section on a UIView?

I want to simulate the behavior of a selected UITableViewCell (in blue) on a UIView, is there a way to do that i.e., when user tap on the UIView, it's like tap on a tableview cell. The view will be highlighted using the same blue color.

Upvotes: 1

Views: 906

Answers (1)

jonkroll
jonkroll

Reputation: 15722

First it's useful to look at how a UITableView cell behaves:

  • When the cell is touched the background color changes to blue and remains blue while the touch is in progress
  • If the location of the touch moves (i.e. the user moves his finger while it is pressed down) the cell background returns to white
  • If the user touches the cell and lifts up his finger without changing the location of the touch, a UIControlEventTouchUpInisde control event is fired

So how can we simulate this? We can start by subclassing UIControl (which is itself a subclass of UIView). We need to subclass UIControl because our code will need to respond to the UIControl method sendActionsForControlEvents:. This will allow us to call addTarget:action:forControlEvents on our custom class.

TouchHighlightView.h:

@interface TouchHighlightView : UIControl

@end

TouchHighlightView.m:

@implementation TouchHighlightView

- (void)highlight
{
    self.backgroundColor = [UIColor blueColor];
}

- (void)unhighlight
{
    self.backgroundColor = [UIColor whiteColor];
}

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    [self highlight];
}

- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
    [self unhighlight];
}

- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
{
    // assume if background color is blue that the cell is still selected
    // and the control event should be fired
    if (self.backgroundColor == [UIColor blueColor]) {

        // send touch up inside event
        [self sendActionsForControlEvents:UIControlEventTouchUpInside];

        // optional: unlighlight the view after sending control event
        [self unhighlight];
    }
}

example usage:

TouchHighlightView *myView = [[TouchHighlightView alloc] initWithFrame:CGRectMake(20,20,200,100)];

// set up your view here, add subviews, etc

[myView addTarget:self action:@selector(doSomething) forControlEvents:UIControlEventTouchUpInside];  
[self.view addSubview:myView];

This is just a rough start. Feel free to modify it according to your needs. Several improvements could be made to make it nicer for the user depending on its usage. For example, notice when a UITableCell is in a selected (blue) state how the text in the textLabels changes to white.

Upvotes: 4

Related Questions