【问题标题】:UISegmentedControl does not detect segment change in iOS5UISegmentedControl 不检测 iOS5 中的段变化
【发布时间】:2011-12-22 07:43:52
【问题描述】:

我有一个 UISegmentedControl

UIBarButtonItem *flex = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]autorelease];
    bottomSegmentedControl = [[UISegmentedControl alloc] initWithItems:nil];
    [bottomSegmentedControl insertSegmentWithImage:[UIImage imageNamed:@"messages.png"] atIndex:0 animated:YES];
    [bottomSegmentedControl insertSegmentWithImage:[UIImage imageNamed:@"news.png"] atIndex:1 animated:YES];
    [bottomSegmentedControl insertSegmentWithImage:[UIImage imageNamed:@"chart.png"] atIndex:2 animated:YES];
    //bottomSegmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Messages",@"News",@"Chart", nil]];
    //bottomSegmentedControl.tintColor = [UIColor blackColor];
    [bottomSegmentedControl addTarget:self action:@selector(segmentedControlChanged:)forControlEvents:UIControlEventValueChanged];
    bottomSegmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
    bottomSegmentedControl.frame = CGRectMake(0,0,300,30);
    bottomSegmentedControl.momentary = NO;
    [bottomSegmentedControl setSelectedSegmentIndex:0];
    UIBarButtonItem *segButton = [[UIBarButtonItem alloc] initWithCustomView:bottomSegmentedControl];

当我单步执行程序时,[bottomSegmentedControl setSelectedSegmentIndex:0]; 不会触发 UIControlEventValueChanged 事件,这是我在 segmentedControlChanged: 中做一些事情的地方

这曾经在 iOS 4.3 中有效,但在 iOS5 中无效。我该如何解决这个问题?

【问题讨论】:

  • 我认为 UIControlEvenValueChanged 只有在用户实际按下不同的段而不是通过编码更改时才会被调用。无论如何,当您更改“setSelectedSegmentIndex”时,为什么不能只调用您想要被解雇的方法?
  • segmentedControl 发生变化时,我需要交换图像。我假设我的 addTarget: 会选择这个。我有错误的 controlEvent 吗?
  • 不,就像@Caleb 说的那样,这很可能是一个错误,因为我记得在 iOS 4 中这样做过,然后它就起作用了。
  • 我可以采取其他路线吗?
  • 取决于,不确定您的 segmentedControlChanged 中有什么代码:

标签: iphone objective-c ios5 uibarbuttonitem uisegmentedcontrol


【解决方案1】:

此问题已在此处得到解答:https://stackoverflow.com/a/8054774/883413

在 iOS5 中,如果以编程方式更改值,则不再触发来自 UISegmentedControl 的事件,以与其他 UIControls 的行为保持一致。

一个快速的解决方案是添加:

[bottomSegmentedControl sendActionsForControlEvents:UIControlEventValueChanged];

之后

[bottomSegmentedControl setSelectedSegmentIndex:0];

但是它会调用你的选择器

segmentedControlChanged:

iOS 中两次

【讨论】:

  • 你可以随时检测出哪个iOS,然后发送与否。
【解决方案2】:

这似乎是known issue。目前尚不清楚 Apple 将新行为视为功能还是错误。

【讨论】:

  • 我可以采取其他路线吗?
  • 如果您正在调用-setSelectedSegmentIndex:,您已经知道所选索引已更改,因此您可以做任何您想做的事情来响应 UIControlEventValueChanged。
  • 很明显,苹果认为这是一项功能,并且有意将 UISegmentedControl 调整为其他 UIControl 的行为。
猜你喜欢
  • 2017-05-21
  • 1970-01-01
  • 2011-10-03
  • 2012-12-15
  • 1970-01-01
  • 2013-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多