UISegmentedControl以编程方式调用selectedSegmentIndex时调用action方法

我的xib文件中有一个UISegmentedControl。 它链接到xib文件中值更改事件的操作方法。

当我以编程方式设置selectedSegmentIndex的值时,将调用action方法

mysegmentedcontrol.selectedSegmentIndex = index 

我期待只有当用户通过触摸来更改控件时才会调用操作方法?

这仅适用于UISegmentedControl。

.h文件

 BOOL isProgramaticallyChanged; 

.m文件

 - (IBAction)segmentAction:(id)sender { // valuechanged connected function UISegmentedControl *segControll = (UISegmentedControl *)sender; if (segControll.tag == 55) { // while create segment specify tag value to 55 (to set use via IB or Code) if (isProgramaticallyChanged == NO) { // your valuechanged code here } else { isProgramaticallyChanged = NO; //important } } else if (segControll.tag == 66) { // for many segments } //...like this do for all segments } 

在.m文件中

无论你把这个代码以编程方式进行更改,都要在此之前做到这一点

 if (mysegmentedcontrol.selectedSegmentIndex != index) { isProgramaticallyChanged = YES; mysegmentedcontrol.selectedSegmentIndex = index; } 

解决方案可能是将IBAction方法链接到touchUpInside事件,并在计划以编程方式更改所选索引时将值更改传播到那里。

根据我们在Cocoa基础指南中可以阅读的内容,来自UI控件的事件应仅在事件被触发以响应用户对控件执行操作时发送,而不是从程序更改中发送。 这是我的误解,或者是某种UISegmentedControl错误。

我的解决方案更详细

IBAction方法连接到UISegmentedControlTouch Up Inside事件,并将sender参数转发到处理Value Changed的操作方法。 这样,如果值的程序化更改,控件将不会调用值更改处理程序。 只有当它通过控件上的即时用户操作时才会出现。

这里要解决的唯一问题是检测所选索引是否实际发生了变化。

我会在答案中添加更多内容,这些答案可能会更加可控。 只需调用removeTarget,对所选段进行编程更新,重新添加目标(对于UIControlEventValueChanged)

我来到这里寻找答案,提供的答案似乎有效,但后来我发现删除/添加目标感觉更合适并且有效。