我可以覆盖UISegmentedControl的UIControlEventTouchUpInside吗?

时间:2009-08-06 21:32:08

标签: 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");
}

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

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

-S

2 个答案:

答案 0 :(得分:5)

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

BOOL _actionSent;

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

- (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;
    }
}

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

答案 1 :(得分:-1)

将UIControlEventValueChanged与UISegmentedControls一起使用。