UISegmentedControl 常用來取代只有少量選項的單選按鈕。它不建議指定 frame,通常會在加入父視圖後由 Auto Layout 或手動位置決定大小。若需要調整單一 segment 寬度,可用 setWidth:forSegmentAtIndex:。
UISegmentedControl *mySegmentedControl = [[UISegmentedControl alloc] initWithItems:nil]; [mySegmentedControl setWidth:100 forSegmentAtIndex:0];
segmentedControlStyle 可控制整體風格,例如 Plain、Bordered、Bar、Bezeled。若使用 Bar 風格,還可以透過 tintColor 為整個控制項染色。
UIColor *myTint = [[UIColor alloc] initWithRed:0.66 green:1.0 blue:0.77 alpha:1.0]; mySegmentedControl.tintColor = myTint;
每個 segment 都是一個按鈕,可包含文字或圖片。可用 insertSegmentWithTitle:atIndex:animated: 或 insertSegmentWithImage:atIndex:animated: 新增,也可用 removeSegmentAtIndex:animated: 刪除。
[mySegmentedControl insertSegmentWithTitle:@"First" atIndex:0 animated:YES]; [mySegmentedControl insertSegmentWithImage:[UIImage imageNamed:@"pic"] atIndex:1 animated:YES];
selectedSegmentedIndex 可取得目前選取的索引。若希望點擊後立刻釋放,可把 momentary 設為 YES,但這會讓 selectedSegmentedIndex 不再更新。事件可透過 addTarget:action:forControlEvents: 搭配 UIControlEventValueChanged 處理。
[mySegmentedControl addTarget:self action:@selector(selected:) forControlEvents:UIControlEventValueChanged];