Custom UISlider: avoid updating when dragging outside

强颜欢笑 提交于 2019-12-06 03:34:36

Simply interrupt the touches methods in your custom subclass and only forward the touches you want acted on to the superclass, like so:

in .h:

@interface CustomSlider : UISlider
@end

in .m:

#import "CustomSlider.h"
@implementation CustomSlider
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    CGPoint touchLocation = [[touches anyObject] locationInView:self];
    if (touchLocation.x < 0 || touchLocation.y<0)return;
    if (touchLocation.x > self.bounds.size.width || touchLocation.y > self.bounds.size.height)return;
    [super touchesBegan:touches withEvent:event];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    CGPoint touchLocation = [[touches anyObject] locationInView:self];
    if (touchLocation.x < 0 || touchLocation.y<0)return;
    if (touchLocation.x > self.bounds.size.width || touchLocation.y > self.bounds.size.height)return;
    [super touchesMoved:touches withEvent:event];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    CGPoint touchLocation = [[touches anyObject] locationInView:self];
    if (touchLocation.x < 0 || touchLocation.y<0)return;
    if (touchLocation.x > self.bounds.size.width || touchLocation.y > self.bounds.size.height)return;
    [super touchesEnded:touches withEvent:event];
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
    CGPoint touchLocation = [[touches anyObject] locationInView:self];
    if (touchLocation.x < 0 || touchLocation.y<0)return;
    if (touchLocation.x > self.bounds.size.width || touchLocation.y > self.bounds.size.height)return;
    [super touchesCancelled:touches withEvent:event];
}
@end

Please note that this implementation will start updating the control if your finger moves back to the control. To eliminate this, simply set a flag if a touch is received outside of the view then check that flag in subsequent touches methods.

You need to set a [slider addTarget:self action:@selector(eventDragOutside:) forControlEvents:UIControlEventTouchDragOutside];

And add a function

- (IBAction)eventDragOutside:(UISlider *)sender { sender.value = 0.0f; }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!