UISegmentedControl 的使用

直接上代码:

//UISegmentedControl 对象的创建
    //參数为数组,数组为字符串数组,表示各个分段的标题。数组的对象个数确定了分段个数。
    UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWithItems:@[@"黄色", @"红色", @"(~﹃~)~zZ", @"☺"]];
    segmentControl.frame = CGRectMake(30, 100, CGRectGetWidth(self.view.bounds) - 60, 40);
    //设置选中分段的下标
    segmentControl.selectedSegmentIndex = 1;
    //当设置完默认选中的下标后。为了可以把响应方法,须要手动调用相应的方法,并把当前分段空间对象当做參数传入方法,方法内部就会依据该分段控件的选中下标做出操作。
    [self handleSegmentAction:segmentControl];
    //通过设置分段控件的表面着色来改动其外观颜色。而且选中颜色随着边框颜色的改变而改变
    segmentControl.tintColor = [UIColor blackColor];
    //背景颜色
//    segmentControl.backgroundColor = [UIColor brownColor];

    //当给分段加入图片时。须要更改 image 对象的渲染模式为原始渲染模式。否则该图片会尾随控件的 tintColor 变成纯色色块,
    UIImage *firstImage = [[UIImage imageNamed:@"2"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    //设置指定分段下标的图片
    [segmentControl setImage:firstImage forSegmentAtIndex:0];

    //绑定响应方法
    [segmentControl addTarget:self action:@selector(handleSegmentAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:segmentControl];
    [segmentControl release];


- (void)handleSegmentAction:(UISegmentedControl *)sender {
    switch (sender.selectedSegmentIndex) {
        case 0:
            self.view.backgroundColor = [UIColor yellowColor];
            NSLog(@"黄色");
            break;
        case 1:
            self.view.backgroundColor = [UIColor redColor];
            NSLog(@"红色");
            break;
        case 2:
            self.view.backgroundColor = [UIColor blueColor];
            NSLog(@"蓝色");
            break;
        case 3:
            self.view.backgroundColor = [UIColor greenColor];
            NSLog(@"绿色");
            break;
    }
    NSLog( @"%s", __FUNCTION__ ) ;
}
posted @ 2017-08-02 21:05  yangykaifa  阅读(290)  评论(0编辑  收藏  举报