UISlider that snaps to a fixed number of steps (like Text Size in the iOS 7 Settings app)

前端 未结 6 2213
情深已故
情深已故 2020-12-04 06:31

I\'m trying to create a UISlider that lets you choose from an array of numbers. Each slider position should be equidistant and the slider should snap to each po

6条回答
  •  长情又很酷
    2020-12-04 06:48

    The answer is essentially the same at this answer to UISlider with increments of 5

    To modify it to work for your case, you'll need to create a rounding function that returns only the values you want. For example, you could do something simple (though hacky) like this:

    -(int)roundSliderValue:(float)x {
        if (x < -1.5) {
            return -3;
        } else if (x < 1.0) {
            return 0;
        } else if (x < 3.0) {
            return 2;
        } else if (x < 5.5) {
            return 4;
        } else if (x < 8.5) {
            return 7;
        } else if (x < 11.0) {
            return 10;
        } else {
            return 12;
        }
    }
    

    Now use the answer from the previous post to round the value.

    slider.continuous = YES;
    [slider addTarget:self
          action:@selector(valueChanged:) 
          forControlEvents:UIControlEventValueChanged];
    

    Finally, implement the changes:

    -(void)valueChanged:(id)slider {
        [slider setValue:[self roundSliderValue:slider.value] animated:NO];
    }
    

提交回复
热议问题