3

如何在 UISlider 轨道上获取事件?我能够在 UISlider 的按钮上获得事件,但不在轨道上。我应该怎么做?

谢谢

4

4 回答 4

4

为此,您需要子类化UISlider并实现 touches 事件,例如:touchesBegan、touchesEnd、touchesCancelled、touchesMoved 等。

@interface yourSlider:UISlider
@end

@implementation yourSlider
  - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
    }

  - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
    {
    }

  - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    {
    }

  - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
    {
    }
@end
于 2012-12-17T13:01:00.657 回答
1

子类化UISlider并覆盖其touchesBegan:withEvent:方法。从触摸事件中获取点值并通过点的 .x 值相对于滑块的宽度计算它的百分比。

于 2012-12-17T13:00:41.307 回答
1

答案是正确的,但这里有一个解决方法,您可以简单地在滑块上​​添加一个等于滑块坐标的清除按钮并检测其上的触摸点,然后将 X 位置转换为滑块值。

    - (IBAction)buttonPressed:(id)sender forEvent:(UIEvent*)event
     {
       UIView *button = (UIView *)sender;
       UITouch *touch = [[event touchesForView:button] anyObject];
       CGPoint location = [touch locationInView:button];
       NSLog(@"Location in button: %f, %f", location.x, location.y); \\ use this x to determine slider's value

      }
于 2013-01-06T11:25:37.713 回答
1

另一种解决方法:

    UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self             action:@selector(sliderTapped:)];
gr.delegate=self;
[Slider addGestureRecognizer:gr];

-(void)sliderTapped:(UIGestureRecognizer*)g{
UISlider* s = (UISlider*)g.view;
if (s.highlighted)
    return; 
CGPoint pt = [g locationInView: s];
CGFloat value = s.minimumValue + pt.x / s.bounds.size.width * (s.maximumValue - s.minimumValue);
[s setValue:value animated:YES];
}
于 2013-01-06T13:53:52.200 回答