我在我的项目中使用UISlider
。通常,一旦我们触摸并拖动拇指,拇指就会移动。但是,在我的情况下,当我触摸它的边缘而不接触它时,拇指移动了。像这样:
这是我的代码:
self.slider = [[UISlider alloc] initWithFrame:CGRectMake(30, [UIScreen mainScreen].bounds.size.height - 200, [UIScreen mainScreen].bounds.size.width-30, 30)];
[self.view addSubview:self.slider];
为什么大拇指移动以及如何处理它?我的目标是,只有当我触摸并拖动它时,拇指才会移动,当我触摸它的边缘时,拇指不会移动。
答案 0 :(得分:1)
尝试添加以下代码:
- (void)viewDidLoad
{
UITapGestureRecognizer *tapGest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sliderTapped:)];
[slider addGestureRecognizer:tapGest];
}
- (void)sliderTapped:(UIGestureRecognizer *)tapGest
{
UISlider* slider = (UISlider*)tapGest.view;
if (slider.highlighted)
return; // tap on thumb, let slider deal with it
CGPoint pt = [tapGest locationInView: slider];
CGFloat percentage = pt.x / slider.bounds.size.width;
CGFloat delta = percentage * (slider.maximumValue - slider.minimumValue);
CGFloat value = slider.minimumValue + delta;
[slider setValue:value animated:YES];
}
答案 1 :(得分:0)
为此您需要将taoGesture与UISlider
一起使用,因此首先在滑块对象中添加UITapGestureRecognizer
,然后在gestureRecognizer选择器的action方法中设置其值。
在视图中添加滑块后添加以下代码。
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onSliderTap:)];
[self.slider addGestureRecognizer:tapGestureRecognizer];
现在在onSliderTap
中,您可以获取位置点,然后更新滑块的值
- (void)onSliderTap:(UITapGestureRecognizer *)recognizer {
float width = self.slider.frame.size.width;
CGPoint point = [recognizer locationInView:recognizer.view];
CGFloat sliderX = self.slider.frame.origin.x;
float newValue = ((point.x - sliderX) * self.slider.maximumValue) / width;
[self.slider setValue:newValue];
}