2012-08-16 69 views
-1

我在iPad上的工具欄中添加UISegmentedControl有一些奇怪的問題。我已創建了根控制器,它有以下方法一個UINavigationController:如何以編程方式在iPad上的工具欄中添加UISegmentedControl

- (void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 

    UINavigationController *navigationController = [self navigationController]; 
    navigationController.toolbar.barStyle = UIBarStyleBlackOpaque; 
    navigationController.toolbarHidden = NO; 
} 

- (NSArray *)toolbarItems 
{ 
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:NULL]; 
    return [NSArray arrayWithObjects:[self segmentedControlItem], flexibleSpace, nil]; 
} 

- (UISegmentedControl *)segmentedControl 
{ 
    if (_segmentedControl) { 
     return _segmentedControl; 
    } 

    NSArray *items = [NSArray arrayWithObjects:@"Segment 1", @"Segment 2", nil]; 
    _segmentedControl = [[UISegmentedControl alloc] initWithItems:items]; 
    _segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; 

    return _segmentedControl; 
} 

- (UIBarButtonItem *)segmentedControlItem 
{ 
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:self.segmentedControl]; 
    buttonItem.style = UIBarButtonItemStyleBordered; 
    return buttonItem; 
} 

但控制器後出現的segmentedControl不是工具欄上可見。如何解決它?我已經檢查segmentedControl是否存在於工具欄項目中,它有大小,沒有隱藏,但我看不到它。

(lldb) po [[[[[self navigationController] toolbar] items] objectAtIndex:0] customView] 
(id) $3 = 0x08e39a10 <UISegmentedControl: 0x8e39a10; frame = (7 8; 300 30); opaque = NO; layer = <CALayer: 0x8e63230>> 
+0

你爲什麼不使用IB? – 2012-08-16 11:14:44

+0

好問題,但生成視圖控制器時我有很多自定義邏輯。因此,以編程方式處理它似乎更容易。 – voromax 2012-08-16 11:36:11

+0

downvoting的一些原因會很好... – voromax 2012-12-07 17:22:06

回答

0

我有一個解決方法。如果您想在工具欄中添加UISegmentedControl,覆蓋- (NSArray *)toolbarItems似乎不安全。最好在控制器加載後在某處添加一些方法來配置工具欄。

- (void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 
    [self configureToolbar]; 
} 

- (void)configureToolbar 
{ 
    UINavigationController *navigationController = [self navigationController]; 
    navigationController.toolbar.barStyle = UIBarStyleBlackOpaque; 
    navigationController.toolbarHidden = NO; 
    // Add toolbar items here 
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:NULL]; 
    self.toolbarItems = [NSArray arrayWithObjects:[self segmentedControlItem], flexibleSpace, nil]; 
} 

這種方法可以讓你得到的結果

相關問題