初始化UISegmentedControl
NSArray *arr = [[NSArray alloc]initWithObjects:@"轻拍",@"长按",@"清扫",@"旋转",@"捏合",@"拖拽", nil];
//先创建一个数组用于设置标题
UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:arr];
//在没有设置[segment setApportionsSegmentWidthsByContent:YES]时,每个的宽度按segment的宽度平分
segment.frame = CGRectMake(0, 400, 320, 40);
//设置frame
管理Segment的内容
[segment setTitle:@"大便" forSegmentAtIndex:3];
//设置下标为3的segment的标题 下标以0开始 IOS里的所有下标都是以0开始
[segment setImage:[UIImage imageNamed:@"3"] forSegmentAtIndex:4];
//设置下标为4的segment的图片
管理Segments
[segment insertSegmentWithImage:[UIImage imageNamed:@"3"] atIndex:2 animated:YES]; //设置图片
[segment insertSegmentWithTitle:@"ddd" atIndex:0 animated:YES];//设置标题
[segment numberOfSegments];//得到segment的数量
[segment removeAllSegments];//移出所有segment
[segment removeSegmentAtIndex:2 animated:YES];//移出下标为2的segment
segment.selectedSegmentIndex = 0;//选中第几个segment 一般用于初始化时选中
管理Segment的行为和外观
segment.momentary = NO;
//默认为NO 当设置为YES时,当被选中后,一会儿后不显示被选中状态(最左边的样子),不选中状态即下图的右边几个按钮一样
segment.segmentedControlStyle = UISegmentedControlStyleBar;
typedef enum {
UISegmentedControlStylePlain,
UISegmentedControlStyleBordered,
UISegmentedControlStyleBar,
UISegmentedControlStyleBezeled,
} UISegmentedControlStyle;
//设置样式 当为Bordered和Bar时tintColor才有效 下图为tintcolor为红色时的样子
//Bar样式
//Bordered
[segment setEnabled:NO]; //设置segment是否可用 此方法是其父类UIControl的方法
[segment setEnabled:NO forSegmentAtIndex:2];//设置下标为2的segment不可用
[segment setWidth:100 forSegmentAtIndex:2]; //这时下表为2的segment的宽度
[segment setContentOffset:CGSizeMake(10, 10) forSegmentAtIndex:2];//设置内容偏移
segment.apportionsSegmentWidthsByContent = YES; //是否根据segment的内容改变segment的宽度
自定义外观
[segment setTintColor:[UIColor redColor]]; //设置segments的颜色
[segment setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
typedef enum {
UIBarMetricsDefault, //竖屏
UIBarMetricsLandscapePhone, 横屏
} UIBarMetrics;
//设置在某个状态下segments的背景图片
[segment setTitleTextAttributes:dic forState:UIControlStateNormal];
NSString *const UITextAttributeFont; value: UIFont
NSString *const UITextAttributeTextColor; value: UIColor
NSString *const UITextAttributeTextShadowColor; value: UIColor
NSString *const UITextAttributeTextShadowOffset; value: NSValue wrapping a UIOffset
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor],UITextAttributeTextColor,[UIFont fontWithName:@"SnellRoundhand-Bold" size:24],UITextAttributeFont ,nil];
//设置标题的颜色 字体和大小 阴影和阴影颜色
[segment addTarget:self action:@selector(change:) forControlEvents:UIControlEventValueChanged];
//当选中不同的segment时,会执行change:方法
UISegmentedControl(转),布布扣,bubuko.com