UISegmentedControl 基本属性,

本文详细介绍了如何在Objective-C中创建一个分段控件,并通过添加点击事件控制器来响应用户的操作。包括初始化分段控件、设置其样式、绑定点击事件及实现相应的响应方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

初始化

 NSArray *array=@[@"红",@"黄",@"蓝"];
    //数组中有多少个元素,分段控制就有多少条目(分段)
    self.seg=[[UISegmentedControl alloc] initWithItems:array];
    self.seg.frame=CGRectMake(50, 100, 200, 50);
    //选中哪一个分段
    self.seg.selectedSegmentIndex=1;
    //改变选中时颜色,字体,边框颜色.
    self.seg.tintColor=[UIColor blackColor];
    //改变背景颜色
   // self.seg.backgroundColor=[UIColor greenColor];
    [self addSubview:self.seg];
    

    TestView *test=[[TestView alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.seg.frame), self.seg.frame.origin.y+CGRectGetHeight(self.seg.frame)+20, CGRectGetWidth(self.seg.frame), CGRectGetHeight(self.seg.frame)+200)];
    test.backgroundColor=[UIColor blueColor];
    test.tag=101;
    [self addSubview:test];

点击事件控制器

    [self.rv.seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged ];

实现方法

-(void)segAction:(UISegmentedControl *)sender{

    //打印分段下标
    NSLog(@"%d",sender.selectedSegmentIndex);
    
    NSLog(@"%@",[sender titleForSegmentAtIndex:sender.selectedSegmentIndex]);
    //设置分段上的字符串
    NSArray *arr=@[@"红色",@"黄色",@"蓝色"];
    [sender setTitle:arr[sender.selectedSegmentIndex] forSegmentAtIndex:sender.selectedSegmentIndex];
    /*
    if (sender.selectedSegmentIndex==0) {
        
    
    [self.rv viewWithTag:101].backgroundColor=[UIColor redColor];
    
    }
    if (sender.selectedSegmentIndex==1) {
        
        
        [self.rv viewWithTag:101].backgroundColor=[UIColor yellowColor];
        
    }
    if (sender.selectedSegmentIndex==2) {
        
        
        [self.rv viewWithTag:101].backgroundColor=[UIColor blueColor];
        
    }
    */
    NSArray *colorArray=@[[UIColor redColor],[UIColor yellowColor],[UIColor blueColor]];
    [self.rv viewWithTag:101].backgroundColor=colorArray[sender.selectedSegmentIndex];
    
    [self.rv viewWithTag:102].backgroundColor=[UIColor colorWithRed:self.num green:self.num1 blue:self.num2 alpha:self.num3];
    
    
    
    
    
   

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值