如何在 UISlider 轨道上获取事件?我能够在 UISlider 的按钮上获得事件,但不在轨道上。我应该怎么做?
谢谢
为此,您需要子类化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
子类化UISlider
并覆盖其touchesBegan:withEvent:
方法。从触摸事件中获取点值并通过点的 .x 值相对于滑块的宽度计算它的百分比。
答案是正确的,但这里有一个解决方法,您可以简单地在滑块上添加一个等于滑块坐标的清除按钮并检测其上的触摸点,然后将 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
}
另一种解决方法:
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];
}