Reputation: 2941
I'm trying to create a toggle button in a navigation bar in iOS5 with UISegmentControl. The problem I'm having is that setSelectedSegmentIndex isn't persistent, i.e. when the users clicks one of the segments, it's action gets called but it isn't set as selected. My current code looks like this:
// In viewDidLoad
toolSegment = [[UISegmentedControl alloc] initWithItems:
[NSArray arrayWithObjects:
[UIImage imageNamed:@"ToolPenIcon.png"],
[UIImage imageNamed:@"TextIcon.png"],
nil]];
[toolSegment addTarget:self action:@selector(changeMode:) forControlEvents:UIControlEventValueChanged];
toolSegment.frame = CGRectMake(0, 0, 85, 30);
toolSegment.segmentedControlStyle = UISegmentedControlStyleBezeled;
toolSegment.momentary = YES;
[toolSegment setSelectedSegmentIndex:1];
UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView:toolSegment];
self.navigationItem.rightBarButtonItem = segmentBarItem;
self.navigationController.navigationBar.tintColor = [UIColor blackColor];
- (void)changeMode:(id)sender
{
UISegmentedControl * control = (UISegmentedControl*)sender;
if (control.selectedSegmentIndex == 0) {
NSLog(@"Print");
[toolSegment setSelectedSegmentIndex:0];
} else {
// Should change the selected index.
[toolSegment setSelectedSegmentIndex:1];
[pageView changeToText];
if (pageView.canvas.image != nil) {
[self createNewPage];
}
writing = YES;
}
}
Any tips on what I might be doing wrong would be appreciated.
Upvotes: 0
Views: 4401
Reputation: 33048
You probably don't want the control to be in momentary
mode as this would allow multi selection. Set momentary
to NO
.
Upvotes: 2