我想让 UISlider 响应点击minimumValueImage
and/or maximumValueImage
,将值设置为最小值或最大值。对于这种情况,我似乎找不到“正常”的方法,所以我想出了这个解决方案。我正在继承 UISlider 并记录用户开始触摸的位置。通过比较位置,我可以确定它是否在其中一张图像上。工作正常,但是否有一种不那么定制的方法来实现相同的目标?
@interface FGSlider ()
@property (nonatomic) CGRect minimumValueImageRect;
@property (nonatomic) CGRect maximumValueImageRect;
@property (nonatomic) BOOL touchesBeganInMinimumValueImageRect;
@property (nonatomic) BOOL touchesBeganInMaximumValueImageRect;
@end
@implementation FGSlider
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self];
if(CGRectContainsPoint(self.minimumValueImageRect, location)) {
self.touchesBeganInMinimumValueImageRect = YES;
}
else if(CGRectContainsPoint(self.maximumValueImageRect, location)) {
self.touchesBeganInMaximumValueImageRect = YES;
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesEnded:touches withEvent:event];
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self];
if(self.touchesBeganInMinimumValueImageRect && CGRectContainsPoint(self.minimumValueImageRect, location)) {
[self setValue:self.minimumValue animated:YES];
[self sendActionsForControlEvents:UIControlEventValueChanged];
}
else if(self.touchesBeganInMaximumValueImageRect && CGRectContainsPoint(self.maximumValueImageRect, location)) {
[self setValue:self.maximumValue animated:YES];
[self sendActionsForControlEvents:UIControlEventValueChanged];
}
// reset state
self.touchesBeganInMinimumValueImageRect = NO;
self.touchesBeganInMinimumValueImageRect = NO;
}
-(CGRect)minimumValueImageRectForBounds:(CGRect)bounds {
self.minimumValueImageRect = [super minimumValueImageRectForBounds:bounds];
return self.minimumValueImageRect;
}
-(CGRect)maximumValueImageRectForBounds:(CGRect)bounds {
self.maximumValueImageRect = [super maximumValueImageRectForBounds:bounds];
return self.maximumValueImageRect;
}
@end