2011-06-15 47 views
1

我一直在主要的程序設計方法中創建我的應用程序,並試圖將UISegmentedControl添加到UINavigationControl工具欄。我已經創建並顯示了視圖,以及何時選擇了UISegmentedControl的操作。問題是我在任何時候調用selectedSegmentIndex,它返回一個空值。任何想法爲什麼?UISegmentedControl空指數

NSArray *segmentArray = [[NSArray alloc] initWithObjects:@"Factory Laods", @"User Loads", nil]; 

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems: segmentArray]; 

segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; 
[segmentedControl addTarget:self action:@selector(action:) forControlEvents:UIControlEventValueChanged]; 

    UIBarButtonItem *segmentedButton = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl]; 
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; 

NSArray *array = [[NSArray alloc] initWithObjects:flexibleSpace, segmentedButton, flexibleSpace, nil]; 
[self setToolbarItems:array]; 

--------動作方法------------

- (void) action:(id)sender { 

UISegmentedControl *segment = (UISegmentedControl *) sender; 
NSLog(@"Button %@", [segment selectedSegmentIndex]); 

}

的flexibleSpace對象是一個的UIBarButtonItem初始化爲只是一個靈活的空間來集中UISegmentedControl。添加這個項目後,我可以添加一條NSLog語句併爲selectedSegmentIndex標識一個空值,並且在操作方法中觸發並檢查該事件時它也爲空。謝謝!

+0

你是如何實施行動方法的? – 2011-06-15 22:09:06

回答

1

您的操作方法可能有助於查看,但在上面的代碼中,您已將segmentedButton包括到您設置了工具欄項目的數組中,但您將其創建爲segmentedControl

可能是一個錯字,或您的問題!

+0

這是我用來創建一個欄按鈕項目的代碼添加到工具欄,因此segmentedButton被添加。我不需要這樣做嗎? 'UIBarButtonItem * segmentedButton = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl]; UIBarButtonItem * flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; NSArray * array = [[NSArray alloc] initWithObjects:flexibleSpace,segmentedControl,flexibleSpace,nil]; [self setToolbarItems:array]; [delegate.navController setToolbarHidden:NO animated:YES];' – Andrew 2011-06-16 04:36:51

+0

我在原來的問題中添加了更多的代碼。但我不知道我在做什麼錯,仍然得到返回的空值。 – Andrew 2011-06-16 05:31:23

+0

啊對,那就解釋一下吧。這個問題看起來是傑勒米在他的回答中提到的。 'selectedSegmentIndex'返回一個'int'。如果你在你的action方法中將NSLog語句修改爲NSLog(@「Button%d」,[segmentedControl selectedSegmentIndex]);'會發生什麼? – deftangel 2011-06-16 11:24:37

1

selectedSegmentIndex返回一個NSInteger,而不是一個對象。 A NULL索引是索引0,即,第一段當前被選擇。

此外,這條線漏項數組:

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] 
     initWithItems: 
       [[NSArray alloc] initWithObjects: @"Item 1", @"Item 2", nil]]; 

的所屬基準由-initWithObjects:返回並沒有相應release如下。您可以使用-arrayWithObjects:或將返回的數組分配給臨時變量,以便在初始化分段控件後釋放它。

+0

感謝您的提示,我知道我正在泄漏,只是還沒有得到修復它:P – Andrew 2011-06-16 04:42:13