今天我們來說下iOS中的分段選擇控制器UISegmentedControl,這一控件有什么作用呢
- 每個segment都能被點擊,相當於集成了多個button
- 通常我們會點擊不同的segment來切換不同的view
那么它實現了一個什么效果呢,我們先看下圖:

這就是我們實現的效果,這里家具、燈飾等等每一項就是一個按鈕,點擊會觸發不同事件或跳轉到不同頁面
那么怎么實現這一效果能,只需要簡單幾句代碼:
//先生成存放標題的數據 NSArray *array = [NSArray arrayWithObjects:@"家具",@"燈飾",@"建材",@"裝飾", nil]; //初始化UISegmentedControl UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:array]; //設置frame segment.frame = CGRectMake(10, 100, self.view.frame.size.width-20, 30); //添加到視圖 [self.view addSubview:segment];
這樣一個簡單的分段控制器就生成了,這樣還不能使用,我們實際開發中需要根據它的屬性去進一步設置.
UISegmentedControl屬性設置
在segment生成后我們可以根據需求在任意位置插入或刪除內容
//添加一個分段(在指定下標下插入,並設置動畫效果) [segment insertSegmentWithTitle:@"五金電料" atIndex:2 animated:NO]; //插入圖片分段 //[segment insertSegmentWithImage:[UIImage imageNamed:@"需要插入圖片的名字"] atIndex:2 animated:YES]; //移除一個分段(根據下標) //[segme removeSegmentAtIndex:0 animated:YES];

插入標題效果
我們還可以設置其他屬性
//根據下標修改分段標題(修改下標為2的分段) [segme setTitle:@"巧克力" forSegmentAtIndex:2]; //根據內容定分段寬度 segme.apportionsSegmentWidthsByContent = YES; //開始時默認選中下標(第一個下標默認是0) segme.selectedSegmentIndex = 2; //控件渲染色(也就是外觀字體顏色) segment.tintColor = [UIColor redColor]; //按下是否會自動釋放: //segment.momentary = YES;

實現的效果
除了以上屬性,我們也可以設置每一個分段的屬性
// 設置指定索引選項的寬度(設置下標為2的分段寬度) [segment setWidth:70.0 forSegmentAtIndex:2]; // 設置分段中標題的位置(0,0點為中心) [segment setContentOffset:CGSizeMake(10,10) forSegmentAtIndex:3];

修改后的效果
當然最重要的是我們要給segment添加事件
//添加事件 [segme addTarget:self action:@selector(change:) forControlEvents:UIControlEventValueChanged];
實現添加的事件
//點擊不同分段就會有不同的事件進行相應 -(void)change:(UISegmentedControl *)sender{ NSLog(@"測試"); if (sender.selectedSegmentIndex == 0) { NSLog(@"1"); }else if (sender.selectedSegmentIndex == 1){ NSLog(@"2"); }else if (sender.selectedSegmentIndex == 2){ NSLog(@"3"); }else if (sender.selectedSegmentIndex == 3){ NSLog(@"4"); }
如果開發中有需求,我們可以讓其在導航欄顯示,只需要我們稍微改變下添加到視圖的方法
//顯示在導航欄上 self.navigationItem.titleView = segmentedControl;

在導航欄實現的效果
這只是我個人總結的UISegmentedControl的一些簡單使用方法,如果有什么問題,還希望大家積極指出,共同進步,謝謝.
文/呼嚕ZR(簡書作者)
原文鏈接:http://www.jianshu.com/p/7d9e4d4368c8
著作權歸作者所有,轉載請聯系作者獲得授權,並標注“簡書作者”。
原文鏈接:http://www.jianshu.com/p/7d9e4d4368c8
著作權歸作者所有,轉載請聯系作者獲得授權,並標注“簡書作者”。