UISegmentedControl分段控件代替了桌面OS上的单选按钮。不过它的选项个数非常有限,因为你的IOS设备屏幕有限。当我们需要使用选项非常少的单选按钮时它很合适。
一、创建
UISegmentedControl* mySegmentedControl = [[UISegmentedControl alloc]initWithItems:nil];
mySegmentedControl setWidth:100 forSegmentAtIndex:0];//设置Item的宽度
mySegmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;//风格
typedef enum { UISegmentedControlStylePlain, // large plain 有灰边的大白按钮,适合偏好设置单元 UISegmentedControlStyleBordered, // large bordered 黑边的大白按钮,适用于表格单元 UISegmentedControlStyleBar, // small button/nav bar style. tintable 小按钮,适合导航栏 UISegmentedControlStyleBezeled, // large bezeled style. tintable } UISegmentedControlStyle;
UIColor *myTint = [[ UIColor alloc]initWithRed:0.66 green:1.0 blue:0.77 alpha:1.0]; mySegmentedControl.tintColor = myTint;
[mySegmentedControl insertSegmentWithTitle:@"First" atIndex:0 animated:YES]; [mySegmentedControl insertSegmentWithTitle:@"Second" atIndex:2 animated:YES];
[mySegmentedControl insertSegmentWithImage:[UIImage imageNamed:@"pic"] atIndex:3 animated:YES];
[mySegmentedControl removeSegmentAtIndex:0 animated:YES];//删除一个片段 [mySegmentedControl removeAllSegments];//删除所有片段
[mySegmentedControl setTitle:@"ZERO" forSegmentAtIndex:0];//设置标题 NSString* myTitle = [mySegmentedControl titleForSegmentAtIndex:1];//读取标题
[mySegmentedControl setImage:[UIImage imageNamed:@"pic"] forSegmentAtIndex:1];//设置 UIImage* myImage = [mySegmentedControl imageForSegmentAtIndex:2];//读取
六、选中分段
分段控件的默认行为是,一旦按钮被选中就一直保持,直到另外一个按钮被选中为止。你可以改变这种默认的行为,变成按钮按下后很快就自动释放。将控件的momentary属性设为YES:
mySegmentedControl.momentary = YES;
mySegmentedControl.selectedSegmentedIndex = 0;
[parentView addSubview:mySegmentedControl];//添加到父视图
self.navigationItem.titleView = mySegmentedControl;//添加到导航栏
int x = mySegmentedControl. selectedSegmentedIndex;
[mySegmentedControl addTarget:self action:@selector(selected:) forControlEvents:UIControlEventValueChanged];
-(void)selected:(id)sender{ UISegmentedControl* control = (UISegmentedControl*)sender; switch (control.selectedSegmentIndex) { case 0: // break; case 1: // break; case 2: // break; default: break; } }
UISegmentedControl *seg = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"设置",@"知道了", nil]];seg.frame = CGRectMake(10,0, CGRectGetWidth(self.view.frame) - 20, 35);
seg.center = isbluetoothOffAlerView.center;
seg.layer.borderColor = [UIColor whiteColor].CGColor;
seg.layer.borderWidth = 2;
seg.tintColor = [UIColor whiteColor];
seg.backgroundColor = [UIColor clearColor];
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName,[UIFont systemFontOfSize:24],NSFontAttributeName,nil];
[seg setTitleTextAttributes:dic forState:UIControlStateNormal];
seg.layer.cornerRadius = 15;
seg.layer.masksToBounds = YES;
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#niaoge.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。