iPhone:Programming UISlider to position at clicked location

后端 未结 6 472
北荒
北荒 2020-12-09 13:59

How to set the slider to clicked position and get the slider value on the clicked location on UISlider in iPhone programming. i know we can drag the slider to that position

6条回答
  •  清歌不尽
    2020-12-09 14:11

    The way I did it is to subclass the slider and check in touchesBegan. If the user taps on the thumb button area (which we track) then ignore the tap, but any where else on the trackbar we do: :

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

提交回复
热议问题