UISegmentedControl null索引

时间:2011-06-15 21:57:43

标签: iphone ios uisegmentedcontrol

我一直在以主要的编程方式创建我的应用程序,并且一直在尝试将UISegmentedControl添加到UINavigationControl工具栏。我创建并显示了视图,并选择了UISegmentedControl时的操作。问题是,在任何时候我调用selectedSegmentIndex,它返回一个空值。有什么想法吗?

    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标识空值,并且在操作方法中触发并检查事件时它也为null。谢谢!

2 个答案:

答案 0 :(得分:1)

您的操作方法可能会有所帮助,但在上面的代码中,您已将segmentedButton包含在您设置工具栏项目的数组中,但您已将其创建为segmentedControl

可能是一个错字,或者你的问题!

答案 1 :(得分:1)

selectedSegmentIndex会返回NSInteger,而不是对象。 NULL索引是索引0,即当前选择了第一个分段。

此外,此行泄漏了项目数组:

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

-initWithObjects:返回拥有引用,后面没有相应的release。您可以使用-arrayWithObjects:或将返回的数组分配给临时变量,以便在初始化分段控件后释放它。