实现如下代码:
- (void)viewDidLoad {
[super viewDidLoad];
segmentedControl=[[UISegmentedControl alloc] initWithFrame:CGRectMake(80.0f, 8.0f, 70.0f, 25.0f) ];
[segmentedControl insertSegmentWithTitle:@"T+" atIndex:0 animated:YES];
[segmentedControl insertSegmentWithTitle:@"T-" atIndex:1 animated:YES];
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.momentary = YES;
segmentedControl.multipleTouchEnabled=NO;
[segmentedControl addTarget:self action:@selector(Selectbutton:) forControlEvents:UIControlEventValueChanged];
UIBarButtonItem *segButton = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
[segmentedControl release];
self.navigationItem.rightBarButtonItem = segButton;
[segButton release];
}
-(void)Selectbutton:(int)sender{
UISegmentedControl *myUISegmentedControl=(UISegmentedControl *)sender;
NSLog(@”!!!!!!!!%d”,myUISegmentedControl.selectedSegmentIndex);
switch (myUISegmentedControl.selectedSegmentIndex) {
case 1:
break;
case 0:
break;
default:
break;
}
}
segmentedControl 中的字体也是可以改动的,代码如下:
-(void)ChangeSegmentFont:(UIView *)aView
{
if ([aView isKindOfClass:[UILabel class]]) {
UILabel *lb = (UILabel *)aView;
[lb setTextAlignment:UITextAlignmentCenter];
[lb setFrame:CGRectMake(0, 0, 80, 25)];
[lb setFont:[UIFont systemFontOfSize:18]];
}
NSArray *na = [aView subviews];
NSEnumerator *ne = [na objectEnumerator];
UIView *subView;
while (subView = [ne nextObject]) {
[self ChangeSegmentFont:subView];
}
}
在需要调用此方法的地方加入下面方法即可(分段控件中已经有分段按钮时调用)
[self ChangeSegmentFont:UISegmentedControl的对象];
即可