***UISegmentedControl控件是iOS中比较常用的控件,作为一个iOS手机设备屏幕,一下子放多个UIButton,显然感觉不到美观,作为一个不妥协追求卓越的乔帮主肯定不愿意,所以设计出该控件,以满足平时的需求。***
NSArray *segmentedArray=[[NSArray alloc]initWithObjects:@”一”,@”二”,@”三”,@”四”,nil];
创建UISegmentedControl跟以往的控件相似:
segmentedControl=[[UISegmentedControl alloc]initWithItems:segmentedArray];
segemntedControl.frame=CGRectMake(80,180,250,60);控件初始化并且制定位置
UISegmentedControl控件是一个能深度定制的控件:
segmentedControl.selectedSegmentIndex=1;//默认选中项索引(计数是从0开始的)
segmentedControl.tintColor=[UIColor redColor];//设置背景颜色
segmentedControl.momentary=YES;//设置在点击后是否恢复原样
[self.segmentedControl setTitle:@”YES”forSegmentAtIndex:1];//设置指定索引的标题
[self.view addSubview:segmentedControl];
//设置控件的风格,不过试了下,有警告,不知道是否在ios8中被取消还是被修改了,待定!
segmentedControl.segmentedControlStyle=UISegmentedControlStyleBar;
几种风格:
typedef enum
{
UISegmentedControlStylePlain,
UISegmentedControlStyleBordered,
UISegmentedControlStyleBar,
UISegmentedControlStyleBezeled
}Style;
每一个小段其实就是一个小按钮UIButton,可以为此设置标签、背景、和监听事件
监听事件跟其他控件一样:
[segmentedControl addTarget:self action:@selector(segmentedAction:) forControlEvents:UIControlEventValueChanged];
-(void)segmentedAction:(UISegmentedControl *)Seg
{
NSInteger index=Seg.selectedSegmentIndex;
switch (index) {
case 0:
NSLog(@”%ld”,(long)index);
break;
case 1:
NSLog(@"%ld",(long)index);
break;
case 2:
NSLog(@"%ld",(long)index);
break;
case 3:
NSLog(@"%ld",(long)index);
break;
}
}
[self.segmentedControl setImage:[UIImage imageNamed:@”“] forSegmentAtIndex:3];//设置指定索引的图片
在指定位置添加小段按钮:
[segmentedControl1 insertSegmentWithTitle:@”Add” atIndex:0 animated:YES];
按下是否会自动释放:
segmentedControl1.momentary = YES;
多点触控的支持:
segmentedControl.multipleTouchEnabled=NO;
显示该控件在实际开发中一般为两种情况:
一、显示在普通视图上
[self.view addSubview:segmentedControl];
二、显示在导航栏上、
self.navigationItem.titleView=segmentedControl;