写了一个滑块,默认中间,滑动到左边,滑动到右边,都会触发事件。
WX20201124-161302@2x.png
- (UISlider *)slider {
if (!_slider) {
CGRect rect = CGRectMake((self.width - 120)/2, (self.height - 20)/2, 120, 20);
_slider = [[UISlider alloc] initWithFrame:rect];
[_slider setThumbImage:[UIImage imageNamed:@"滑块-1"] forState:UIControlStateNormal];
[_slider setThumbImage:[UIImage imageNamed:@"滑块-1"] forState:UIControlStateHighlighted];
_slider.minimumTrackTintColor = kWhiteColor;
_slider.maximumTrackTintColor = kWhiteColor;
_slider.value = 0.5;
[_slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventTouchUpInside];
}
return _slider;
}
最终测试的时候,偶发监听不到UIControlEventTouchUpInside事件,网上一搜索全都是这个写法,内容都一样全是抄的,我能想到的是把各抬起事件都监听上,但写有点复杂,终于在各种一样的帖子下找到一条评论。
WX20201124-162047@2x.png
看了一下api尝试使用了continuous一下完美解决。
@property(nonatomic,getter=isContinuous) BOOL continuous; // if set, value change events are generated any time the value changes due to dragging. default = YES
正确的代码如下:
- (UISlider *)slider {
if (!_slider) {
CGRect rect = CGRectMake((self.width - 120)/2, (self.height - 20)/2, 120, 20);
_slider = [[UISlider alloc] initWithFrame:rect];
[_slider setThumbImage:[UIImage imageNamed:@"滑块-1"] forState:UIControlStateNormal];
[_slider setThumbImage:[UIImage imageNamed:@"滑块-1"] forState:UIControlStateHighlighted];
_slider.minimumTrackTintColor = kWhiteColor;
_slider.maximumTrackTintColor = kWhiteColor;
_slider.value = 0.5;
_slider.continuous = NO;
[_slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
}
return _slider;
}
很少用到,有些细节用来记录一下。
网友评论