天天看点

iOS UISegmentedControl 学习

昨天利用UISegmentedControl在写一个项目,效果如下:

iOS UISegmentedControl 学习

1. 以上效果图的源码如下:

- (void)topSegmentInit
{
    //以上通过字典的方式来设置字体大小,颜色等
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys: [CHUtil colorWithHexString:@"ff6230"],
                                                                    UITextAttributeTextColor,
                                                                    [UIFont fontWithName:@"SnellRoundhand-Bold" size:14],
                                                                    UITextAttributeFont ,nil];
    
    NSArray *arr = [[NSArray alloc]initWithObjects:@"发布",@"纪录", nil];
    
   _segment = [[UISegmentedControl alloc]initWithItems:arr];
   _segment.layer.cornerRadius = 3.0;
   _segment.layer.borderWidth = 1.0;
   _segment.layer.borderColor = [[CHUtil colorWithHexString:@"ff6230"]CGColor];
   _segment.frame = CGRectMake((kDEVICEWIDTH - 180)/2.0, 26, 180, 30);
    //整个segment的背景颜色为白色
   [_segment setBackgroundColor:[CHUtil colorWithHexString:@"ffffff"]];
    //设置每次选中的segment的背景颜色
   _segment.tintColor = [CHUtil colorWithHexString:@"ff6230"];
   [_segment setTitleTextAttributes:dic forState:UIControlStateNormal];
   [ _segment addTarget: self
                 action: @selector(controlPressed:)
       forControlEvents: UIControlEventValueChanged ];

   [self.view addSubview:_segment];
    
   //默认选中第0个框
   [_segment setSelectedSegmentIndex:0];
}

- (void) controlPressed:(id)sender
{
    NSInteger   selectedSegment = _segment.selectedSegmentIndex;
    NSLog(@"Segment %ld selected\n", selectedSegment);
}
           

2 .点击时segment 时,可以看到控制台打印如下:

<SourceListViewController.m : 142> -[SourceListViewController controlPressed:]

2015-08-07 09:30:04.291 Shipper[676:7948] Segment 1 selected

-------

<SourceListViewController.m : 142> -[SourceListViewController controlPressed:]

2015-08-07 09:30:05.483 Shipper[676:7948] Segment 0 selected

-------

继续阅读