Yenyi
Yenyi

Reputation: 419

UISegmentedControl not firing with iOS 5

Does anyone else see this issue? I am using a segmented control, and I've overridden it so that when the user hits the same segment(index), it is deselected.

This worked fine in previous versions, but now testing on iOS5. And I am finding that the UIControlEventValueChanged is not sent when you tap on the same segment. So the code works ok when you tap on different segments, but does not for the same segment.

My code.

segmentCtrl = [[MySegmentedControl alloc] initWithItems: segmentCtrlLabels];
segmentCtrl.segmentedControlStyle = UISegmentedControlStyleBar;
// Register for touch events
[segmentCtrl addTarget:self action:@selector(segmentedCtrlTouched:) forControlEvents:UIControlEventValueChanged];

I tried to register for UIControlEventTouchUpInside, and get the same behavior.

Any suggestions for work around?

Regards, Yenyi

Upvotes: 1

Views: 1640

Answers (2)

Leslie Godwin
Leslie Godwin

Reputation: 2658

Yup you need to implement the control events yourself.

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

    [self sendActionsForControlEvents: UIControlEventTouchDown];
}

- (void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event
{
    [super touchesEnded: touches withEvent: event)];

    if (CGRectContainsPoint(self.bounds, [touches.anyObject locationInView: self]))
    {
        [self sendActionsForControlEvents: UIControlEventTouchUpInside];
    }
    else
    {
        [self sendActionsForControlEvents: UIControlEventTouchUpOutside];
    }
}

- (void) touchesCancelled: (NSSet *) touches withEvent: (UIEvent *) event
{
    [super touchesCancelled: touches withEvent: event];

    [self sendActionsForControlEvents: UIControlEventTouchCancel];
}

Upvotes: 0

Yenyi
Yenyi

Reputation: 419

Fixed it by registrering for a touch event. If the touched segment is the same, I manually send the EventChanged event.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{    
NSInteger current = self.selectedSegmentIndex;
[super touchesBegan:touches withEvent:event];

if (current == self.selectedSegmentIndex) {
    [self setSelectedSegmentIndex:current];
    [self sendActionsForControlEvents:UIControlEventValueChanged];
}
}

Upvotes: 1

Related Questions