2009-11-05 419 views
5

任何人可以就如何導航欄中添加分段控制代碼幫助....我已經看到它在某些應用中分段控制與和要實現它添加導航欄

感謝

回答

14

你想使用Interface Builder還是僅使用代碼?

使用IB操作非常簡單,您只需將分段控件拖放到標題所在的導航欄上即可。標題將被分段控制所替代。

如果您想在代碼中完成此操作,請參閱this section of iPhone reference library。您似乎需要將導航項目的titleView屬性設置爲您的分段控件,它是UIView的子類,因此這是完全合法的。

+1

你能不能把更新的鏈接,因爲它已經過時? thx – xon1c 2011-07-12 17:32:36

+0

@ xon1c:好的,完成了 – madej 2011-08-23 10:58:54

1

viewDidLoad

OBJ-C:

NSArray *segmentTitles = @[ 
    @"segment1", 
    @"segment2", 
]; 

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentTitles]; 
segmentedControl.selectedSegmentIndex = 0; 
segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth; 
// change the width from 400.0 to something you want if it's needed 
segmentedControl.frame = CGRectMake(0, 0, 400.0f, 30.0f); 
[segmentedControl addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged]; 

self.navigationItem.titleView = segmentedControl; 

迅速:

let segmentTitles = [ 
    "segment1", 
    "segment2", 
] 

let segmentedControl = UISegmentedControl(items: segmentTitles) 
segmentedControl.selectedSegmentIndex = 0 
segmentedControl.autoresizingMask = UIViewAutoresizing.FlexibleWidth 
// change the width from 400.0 to something you want if it's needed 
segmentedControl.frame = CGRectMake(0, 0, 400.0, 30.0) 
segmentedControl.addTarget(self, action: "segmentChanged:", forControlEvents: UIControlEvents.ValueChanged) 

self.navigationItem.titleView = segmentedControl