开发者

UISegmentedControl null index

开发者 https://www.devze.com 2023-03-13 02:46 出处:网络
I have been creating my application in a primarily programatic approach and have been attempting to add a UISegmentedControl to the UINavigationControl Toolbar. I have the view created and shown and a

I have been creating my application in a primarily programatic approach and have been attempting to add a UISegmentedControl to the UINavigationControl Toolbar. I have the view created and shown and an action for when the UISegmentedControl is selected. The issu开发者_C百科e is that at any point I call selectedSegmentIndex, it returns a null value. Any ideas why?

    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];

-------- action method ------------

- (void) action:(id)sender {

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

}

The flexibleSpace object is a UIBarButtonItem initialized to be just a flexible space to center out the UISegmentedControl. After this item is added I can add an NSLog statement and identify a null value for the selectedSegmentIndex and it's also null when the event is triggered and checked in the action method. Thanks!


Your action method might be helpful to see but in your code above, you've included segmentedButton to the array which you set the toolbar items with but you created it as segmentedControl.

Could be a typo, or your issue!


selectedSegmentIndex returns an NSInteger, not an object. A NULL index is the index 0, i.e., the first segment is currently selected.

Also, this line leaks the item array:

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

An owning reference is returned by -initWithObjects: and no corresponding release follows. You can either use -arrayWithObjects: or assign the returned array to a temporary variable so you can release it after initializing your segmented control.

0

精彩评论

暂无评论...
验证码 换一张
取 消