2012-08-14 55 views
0

为了“抓住”UI滑块的手柄,必须触摸它的顶部。我有兴趣修改行为,以便用户只需触摸uislider中的任何位置即可。触摸时,手柄会跳转到用户触摸的任何位置。我怎样才能做到这一点?UISlider - 选择何时触摸拇指

回答

1

我通过重写touchesBegan来完成它:withEvent:在UISlider的子类中。您不必检查触摸与滑块的距离有多近,因为如果滑块位于滑块上方,您只会触摸一个事件。此代码适用于使用默认的0到1比例设置的滑块。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    float xPoint = [[[event allTouches]anyObject]locationInView:self].x; 
    [self setValue:xPoint/self.frame.size.width]; 
    [super touchesBegan:touches withEvent:event]; 
} 
+0

够简单。谢谢! – morgancodes 2012-08-15 16:27:53

0

关闭我的头顶我会说你应该留意接触视图。当检测到触摸时,请检查它与UISlider机身的接近程度。如果它是在一定范围内,做的(伪)

sliderValue = sliderMinValue + (sliderMaxValue-sliderMinValue)/(xCoordOfTouch - sliderLeftSideXCoord)/sliderLength 

所以基本上你滑块应根据用户触碰相对于滑块的帧中计算值。

你提到这很有趣,因为我在想今天做同样的事情。如果我找到了一些东西,我会发布它(但不要屏住呼吸)。

0

如果您有最小值或最大值的图像,rdelmar的回答不起作用。我修改了rdelmar的touchesBegan:withEvent:方法,只在轨道上看到触及而不在边缘。

希望这有助于

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    float xPoint = [[touches anyObject] locationInView:self].x; 
    float trackWidth = [self trackRectForBounds:self.bounds].size.width; 
    float margin = (self.bounds.size.width - trackWidth)/2; 
    float xOffset = xPoint - margin; 

    if (xOffset >= 0.0 && xOffset <= trackWidth) { 
     float newValue = xOffset/trackWidth; 
     [self setValue:newValue animated:YES]; 
     [super touchesBegan:touches withEvent:event]; 
    } 
} 
1

我知道这是一个老问题,但我只是想提一提,我想出了一个不同的方式最近做到这一点。简而言之:

- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event { 
    BOOL ignored = [super beginTrackingWithTouch:touch withEvent:event]; 
    return YES; 
} 

- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event { 
    BOOL ignored = [super continueTrackingWithTouch:touch withEvent:event]; 
    return YES; 
} 

我认为这是解决问题的一个更安全的方式,因为你不必手动生成滑块的值。你永远不知道苹果什么时候可能会引入整数/制动滑块等。