如何在UISegementedControl上注册UIControlEventTouchUpInside?

Jas*_*son 1 iphone interface-builder uisegmentedcontrol ios

我想UISegmentedControl在事件上注册一个函数UIControlEventTouchUpInside- 不是 UIControlEventValueChanged.我特别希望确保它仅在用户触摸项目时触发,而不是在以编程方式设置其值时触发.

有什么建议?

Jas*_*son 5

我发现,关键是将UISegmentedControl子类化.在正常情况下,UISegmentedControl根本不响应UIControlEventTouchUpInside.通过子类化UISegmentedControl,您可以重新定义touchesEnded函数(实质上是用户触摸对象时触发的函数),如下所示:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    [self.superview touchesEnded:touches withEvent:event];

    MyViewController *vc; // the view controller which contains the UISegmentedControl
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[MyViewController class]]) {
            vc = (MyViewController*)nextResponder;
            break;
        }
    }

    if (vc) {
        [vc myFunction];
    }
} 
Run Code Online (Sandbox Code Playgroud)