UISegmentedControl 常用於多個選項切換的情境。與一次放多個 UIButton 相比,它更適合需要互斥選擇的介面,視覺上也更簡潔。
可以先建立標題陣列,再用 initWithItems: 初始化 segmented control。
NSArray *segmentedArray = @[@"一", @"二", @"三", @"四"];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentedArray];
segmentedControl.frame = CGRectMake(80, 180, 250, 60);它可以像其他 UIControl 一樣,透過 addTarget:action:forControlEvents: 監聽值變化。
[segmentedControl addTarget:self action:@selector(segmentedAction:) forControlEvents:UIControlEventValueChanged];在回呼方法中,可透過 selectedSegmentIndex 判斷目前選取項。
若要執行時新增選項,可使用 insertSegmentWithTitle:atIndex:animated:。
它可以放在一般 view 上,也可以指定給 navigationItem.titleView,作為導覽列中的標題控件。
UISegmentedControl 簡單易用,適合切換型 UI。只要掌握初始化、選取索引、事件綁定與動態新增,就能覆蓋大部分常見需求。