【问题标题】:UISegmentedControl null indexUISegmentedControl 空索引
【发布时间】:2011-06-15 21:57:42
【问题描述】:

我一直在主要以编程方式创建我的应用程序,并一直在尝试将 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 标识一个空值,并且在触发事件并在操作方法中检查时它也为空。谢谢!

【问题讨论】:

  • 你是如何实现action方法的?

标签: iphone ios uisegmentedcontrol


【解决方案1】:

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

可能是拼写错误,也可能是您的问题!

【讨论】:

  • 这是我用来创建条形按钮项以添加到工具栏的代码,因此添加了分段按钮。我不需要这样做吗? 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];
  • 我在原始问题中添加了更多其余代码。但我不知道我做错了什么才能返回空值。
  • 啊,对,那就解释了。这个问题看起来就是杰里米在他的回答中提到的。 selectedSegmentIndex 返回一个 int。如果您将操作方法​​中的 NSLog 语句修改为 NSLog(@"Button %d", [segmentedControl selectedSegmentIndex]); 会发生什么?
  • 哈!这么简单的事情对吧?谢谢大家...我应该知道的更好。我想我只需要第二双眼睛。
【解决方案2】:

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

另外,这一行泄露了 item 数组:

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

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

【讨论】:

  • 感谢您的提示,我知道我在泄漏,只是还没有修复它:P
猜你喜欢
  • 2015-05-23
  • 2011-09-28
  • 2012-11-05
  • 1970-01-01
  • 2012-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多