简体   繁体   中英

How to create a slider that snaps to a selection

How would I go about making a slider that snaps to a selection. I was there to be 3 selections, one on the left, one on the right and one in the middle. When the user drags the slider left a little, it will animate and snap to the left selection. The same effect on the right and in the middle.

If you are familiar with the app UBER, they have something (with 4 sections) that is exactly what I am talking about. Screenshot here (slider on the bottom): http://i.imgur.com/xTPfDcY.png

Any idea how I would implement this? Should I use a UISlider or no?

Thanks a lot, Gabe

Without considering the custom appearance of the Uber slider, you can achieve this "animated snapping" behavior by listening for the Touch Up Inside event (and Touch Up Outside, for completeness' sake) on your slider, and setting its value to the nearest integer value:

- (IBAction)sliderTouchUp:(UISlider *)sender
{
    [sender setValue:floorf([sender value] + 0.5) animated:YES];
}

Setting the minimum value to 1 and the maximum value to 3 will give you three "stops" on the slider, and when the user releases the slider, it will animate to the nearest stop.

The basic idea is that you want to look at the current value of the slider, as the user moves it, and if it falls within your "snap" range, you set the slider's value to the desired location. Something like this:

- (void)sliderUpdated:(UISlider *)slider {
    float val = slider.value;
    if (val>= 0.46 && val <= 0.54) {
        [slider setValue:0.5 animated:YES];
    }
}

Obviously you will need to check three different ranges. The code I posted makes the slider appear to have a detent in the middle. You probably also need to keep track of which direction the slider is being moved so you know to move the slider to the left or right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM