我一直在以一种主要的编程方法创建我的应用程序,并且一直在尝试向UINavigationControl工具栏添加一个UISegmentedControl。我创建并显示了视图,并在选择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标识一个空值,当在操作方法中触发和检查事件时,该值也为空值。谢谢!
发布于 2011-06-16 06:46:04
您的操作方法可能有助于查看,但在上面的代码中,您已经将segmentedButton包含到用于设置工具栏项的数组中,但您将其创建为segmentedControl。
可能是打字错误,也可能是你的问题!
发布于 2011-06-16 06:51:53
selectedSegmentIndex返回一个NSInteger,而不是一个对象。NULL索引是索引0,即当前选择第一个段。
此外,此行还会泄漏item数组:
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]
initWithItems:
[[NSArray alloc] initWithObjects: @"Item 1", @"Item 2", nil]];-initWithObjects:返回一个拥有的引用,后面没有相应的release。您可以使用-arrayWithObjects:或将返回的数组赋给一个临时变量,以便在初始化分段控件后释放它。
https://stackoverflow.com/questions/6364900
复制相似问题