分段控制器相當於桌面系統上的單選按鈕群組,把幾個互斥的選項並排呈現。由於 iOS 螢幕寬度有限,適用的場合是「選項數量很少」的切換,例如列表/網格、日/週/月。
UISegmentedControl *mySegmentedControl = [[UISegmentedControl alloc] initWithItems:nil];
它的初始化器只有 initWithItems:,沒有 initWithFrame:——尺寸會由系統依內容與 Auto Layout 決定。若需要微調,可以指定單一片段的寬度:
[mySegmentedControl setWidth:100 forSegmentAtIndex:0];
mySegmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
typedef enum {
UISegmentedControlStylePlain, // 大尺寸平坦樣式,適合偏好設定頁面
UISegmentedControlStyleBordered, // 大尺寸方框樣式,適合表格儲存格
UISegmentedControlStyleBar, // 小尺寸,適合放在導航列
UISegmentedControlStyleBezeled, // 大尺寸立體樣式
} UISegmentedControlStyle;
使用 Bar 樣式時,可用 tintColor 為整個控制項上色:
UIColor *myTint = [[UIColor alloc] initWithRed:0.66 green:1.0 blue:0.77 alpha:1.0]; mySegmentedControl.tintColor = myTint;
每個片段就是一個帶標題或圖片的按鈕,並以索引做為識別:
[mySegmentedControl insertSegmentWithTitle:@"First" atIndex:0 animated:YES]; [mySegmentedControl insertSegmentWithTitle:@"Second" atIndex:2 animated:YES]; [mySegmentedControl insertSegmentWithImage:[UIImage imageNamed:@"pic"] atIndex:3 animated:YES]; [mySegmentedControl removeSegmentAtIndex:0 animated:YES]; // 移除單一 [mySegmentedControl removeAllSegments]; // 移除全部
[mySegmentedControl setTitle:@"ZERO" forSegmentAtIndex:0]; // 設定標題 NSString *myTitle = [mySegmentedControl titleForSegmentAtIndex:1]; // 讀取標題 [mySegmentedControl setImage:[UIImage imageNamed:@"pic"] forSegmentAtIndex:1]; // 設定圖片 UIImage *myImage = [mySegmentedControl imageForSegmentAtIndex:2]; // 讀取圖片
請注意圖片不會自動縮放,會以原始尺寸呈現,因此素材尺寸必須精確。
預設情況下,被點選的片段會一直保持選取狀態,直到另一個片段被點擊。若希望它像按鈕一樣按完即放,把 momentary 設為 YES:
mySegmentedControl.momentary = YES;
開啟這個模式後,selectedSegmentIndex 不會更新,因此無法再用它取得「目前選中的片段」,需要改在事件回呼中自行判斷。
設定初始選取項(預設沒有任何片段被選中):
mySegmentedControl.selectedSegmentIndex = 0;
[parentView addSubview:mySegmentedControl]; // 加入父視圖 self.navigationItem.titleView = mySegmentedControl; // 放進導航列 int x = mySegmentedControl.selectedSegmentIndex; // 目前選中的索引
[mySegmentedControl addTarget:self
action:@selector(selected:)
forControlEvents:UIControlEventValueChanged];
-(void)selected:(id)sender {
UISegmentedControl *control = (UISegmentedControl *)sender;
switch (control.selectedSegmentIndex) {
case 0:
// 第一個片段的行為
break;
case 1:
// 第二個片段的行為
break;
case 2:
// 第三個片段的行為
break;
default:
break;
}
}
透過 layer 與標題屬性,可以調出白框、透明底、圓角的樣式:
UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:
@[@"設置", @"知道了"]];
seg.frame = CGRectMake(10, 0, CGRectGetWidth(self.view.frame) - 20, 35);
seg.center = isbluetoothOffAlerView.center;
seg.layer.borderColor = [UIColor whiteColor].CGColor;
seg.layer.borderWidth = 2;
seg.layer.cornerRadius = 15;
seg.layer.masksToBounds = YES;
seg.tintColor = [UIColor whiteColor];
seg.backgroundColor = [UIColor clearColor];
NSDictionary *dic = @{
NSForegroundColorAttributeName : [UIColor whiteColor],
NSFontAttributeName : [UIFont systemFontOfSize:24]
};
[seg setTitleTextAttributes:dic forState:UIControlStateNormal];