iPhone:编程UISlider以定位点击位置

sus*_*use 7 iphone uislider

如何将滑块设置为单击位置,并在iPhone编程中的UISlider上单击的位置获取滑块值.我知道我们可以将滑块拖动到那个位置,但我不想这样做.你能告诉我如何将滑块设置为点击位置吗?这可能吗?

mat*_*att 19

以下是"作为用户练习"的部分:

- (void) tapped: (UITapGestureRecognizer*) g {
    UISlider* s = (UISlider*)g.view;
    if (s.highlighted)
        return; // tap on thumb, let slider deal with it
    CGPoint pt = [g locationInView: s];
    CGFloat percentage = pt.x / s.bounds.size.width;
    CGFloat delta = percentage * (s.maximumValue - s.minimumValue);
    CGFloat value = s.minimumValue + delta;
    [s setValue:value animated:YES];
}
Run Code Online (Sandbox Code Playgroud)


pet*_*ept 11

我这样做的方法是将滑块子类化并签入touchesBegan.如果用户点击拇指按钮区域(我们跟踪),则忽略点击,但我们在轨道栏上的任何其他位置:

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

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self];

    // if we didn't tap on the thumb button then we set the value based on tap location
    if (!CGRectContainsPoint(lastKnownThumbRect, touchLocation)) {

        self.value = self.minimumValue + (self.maximumValue - self.minimumValue) * (touchLocation.x / self.frame.size.width);
    }

    [super touchesBegan:touches withEvent:event];
}

- (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value {

    CGRect thumbRect = [super thumbRectForBounds:bounds trackRect:rect value:value];
    lastKnownThumbRect = thumbRect;
    return thumbRect;
}
Run Code Online (Sandbox Code Playgroud)


con*_*are 7

您可以简单地将UITapGestureRecognizer添加到滑块,然后拉出与其关联的UIEvent和Touches,以找出UISlider沿着UISlider发生的位置.然后将滑块的值设置为此计算值.

更新:

首先,设置滑块并为其添加手势识别器.

UISlider *slider = [[[UISlider alloc] init] autorelease];
…
<slider setup>
…
UITapGestureRecognizer *gr = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sliderTapped:)] autorelease];
[slider addGestureRecognizer:gr];
Run Code Online (Sandbox Code Playgroud)

然后实现选择器

- (void)sliderTapped:(UIGestureRecognizer *)gestureRecognizer {
    <left as a user excercise*>
}
Run Code Online (Sandbox Code Playgroud)

*提示:阅读文档以弄清楚如何获得locationInView外推并找出滑块应该是什么