Swift - 分段選擇控制項(UISegmentedControl)的用法_基礎使用
來源:互聯網
上載者:User
1,選擇控制項的建立,並監聽控制項選擇值 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import UIKit class ViewController : UIViewController { override func viewDidLoad() { super .viewDidLoad() //選項除了文字還可以是圖片 let items=[ "選項一" , "選項二" , UIImage (named: "star" )!] as [ AnyObject ] let segmented= UISegmentedControl (items:items) segmented.center= self .view.center segmented.selectedSegmentIndex=1 //預設選中第二項 segmented.addTarget( self , action: "segmentDidchange:" , forControlEvents: UIControlEvents . ValueChanged ) //添加值改變監聽 self .view.addSubview(segmented) } func segmentDidchange(segmented: UISegmentedControl ){ //獲得選項的索引 print (segmented.selectedSegmentIndex) //獲得選擇的文字 print (segmented.titleForSegmentAtIndex(segmented.selectedSegmentIndex)) } }
2,選擇控制項中選項的添加和刪除 1 2 3 4 5 6 //添加文字選項 segmented.insertSegmentWithTitle( "新增選項" ,atIndex:1,animated: true ); //添加圖片選項 segmented.insertSegmentWithImage( UIImage (named: "icon" )!,atIndex:1,animated: true ) //移除選項 segmented.removeSegmentAtIndex(1,animated: true );
3,修改選項顏色(包括圖片選項) 1 segmented.tintColor= UIColor .redColor()
4,修改選項文字 1 segmented.setTitle( "swfit" ,forSegmentAtIndex:1)
5,修改選項圖片 1 segmented.setImage( UIImage (named: "icon" ),forSegmentAtIndex:2)
6,修改選項內容位移位置 1 segmented.setContentOffset( CGSizeMake (10,7),forSegmentAtIndex:1)