IOS學習筆記(七)之UISegmentedControl分段控件的基本概念和使用方法(博客地址:http://blog.csdn.net/developer_jiangqq)
Author:hmjiangqq
Email:jiangqqlmj@163.com
UISegmentedControl
首先看下官網介紹:

A UISegmentedControl object is a horizontal control made of multiple segments, each segment functioning as a discrete button. A segmented control affords
a compact means to group together a number of controls.
A segmented control can display a title (an NSString object)
or an image (UIImage object).
The UISegmentedControl object automatically resizes segments to fit proportionally within their superview unless they have a specific width set. When
you add and remove segments, you can request that the action be animated with sliding and fading effects.
每個段相當於一個獨立的按鈕。這控件一般有兩種樣式-Plain&Bordered樣式和Bar樣式,
Bordered樣式是在Plain樣式上面加上了一個邊框.Plain和Bordered樣式中每一段都可以設置文本
和添加圖片.Bar樣式整體來說比較窄,在其中我們一般不會放置圖片。
常用的屬性和方法如下:


實例代碼如下:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
NSArray *array=@[@"搜索",@"選擇",@"視頻",@"圖片"];
UISegmentedControl *segmentControl=[[UISegmentedControl alloc]initWithItems:array];
segmentControl.segmentedControlStyle=UISegmentedControlStyleBordered;
//設置位置 大小
segmentControl.frame=CGRectMake(60, 100, 200, 40);
//默認選擇
segmentControl.selectedSegmentIndex=1;
//設置背景色
segmentControl.tintColor=[UIColor greenColor];
//設置監聽事件
[segmentControl addTarget:self action:@selector(change:) forControlEvents:UIControlEventValueChanged];
[self.window addSubview:segmentControl];
[segmentControl release];
[self.window makeKeyAndVisible];
return YES;
}
-(void)change:(UISegmentedControl *)segmentControl{
NSLog(@"segmentControl %d",segmentControl.selectedSegmentIndex);
}運行截圖:

