我可以覆盖UISegmentedControl的UIControlEventTouchUpInside吗?

spe*_*wah 2 iphone

我有一个UISegmentedControl,如果你单击已经选中的项目,我想用它来执行某个操作.

我的想法基本上是这样的:

- (void)viewDidLoad {
    UISegmentedControl * testButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"one", @"two", nil]];
    [self.view addSubview:testButton];
    [testButton addTarget:self action:@selector(clicked:) forControlEvents:UIControlEventTouchUpInside];
    [super viewDidLoad];
}

-(void) clicked: (id) sender{
    NSLog(@"click");
}
Run Code Online (Sandbox Code Playgroud)

(在clicked:我点击之前,我只是做一些检查以查看新选择的索引是否与旧的选定索引不同)

问题是我似乎无法覆盖TouchUpInside控件事件的操作.任何帮助赞赏!

-S

小智 5

您可以使用子类来获取所需的行为.创建一个具有一个BOOL ivar的UISegmentedControl的子类:

BOOL _actionSent;
Run Code Online (Sandbox Code Playgroud)

然后,在实现中,重写以下两个方法:

- (void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    [super sendAction:action to:target forEvent:event];
    _actionSent = TRUE;
}

- (void) setSelectedSegmentIndex:(NSInteger)toValue {
    _actionSent = FALSE;

    [super setSelectedSegmentIndex:toValue];

    if (!_actionSent) {
        [self sendActionsForControlEvents:UIControlEventValueChanged];
        _actionSent = TRUE;
    }
}
Run Code Online (Sandbox Code Playgroud)

可能还有其他方法,但这对我来说没问题.我有兴趣了解其他方法.