UISlider子类用于自定义拇指位置和拇指图像?

时间:2017-05-18 09:45:09

标签: ios objective-c

enter image description here

是否可以通过子类化UISlider来实现上面的滑块? 我想让滑块拇指移动到边缘但是还剩下一些空间。 我通过覆盖以下方法实现了自定义位置,但现在拇指没有响应触摸事件。

-(void)awakeFromNib {
    [super awakeFromNib];
    [self setThumbImage:[UIImage imageNamed:IMG_SLIDER_THUMB] forState:UIControlStateNormal];
}

- (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value {
    UIImage* image = self.currentThumbImage;

    CGRect thumbRect = [super thumbRectForBounds:bounds trackRect:rect value:value];

return CGRectMake(thumbRect.origin.x, rect.origin.y+2, image.size.width, image.size.height);
}

2 个答案:

答案 0 :(得分:1)

我通过继承UISlider实现了上面的操作,并且对于触摸事件问题,我在故事板中为滑块添加了高度约束以增加运行时的边界。以下是将滑块移动到边缘和自定义拇指位置的代码:

//Get thumb rect for larger track rect than actual to move slider to edges
-(CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value {
    UIImage *image = self.currentThumbImage;

    rect.origin.x -= SLIDER_OFFSET;
    rect.size.width += (SLIDER_OFFSET*2);
    CGRect thumbRect = [super thumbRectForBounds:bounds trackRect:rect value:value];
    return CGRectMake(thumbRect.origin.x, rect.origin.y+2, image.size.width, image.size.height);
}

//Make track rect smaller than bounds
-(CGRect)trackRectForBounds:(CGRect)bounds  {
    bounds.origin.x += SLIDER_OFFSET;
    bounds.size.width -= (SLIDER_OFFSET*2);
    CGRect trackRect = [super trackRectForBounds:bounds];

    return CGRectMake(trackRect.origin.x, trackRect.origin.y, trackRect.size.width, trackRect.size.height);
}

答案 1 :(得分:0)

我认为代码错了。 首先,您应该获得自定义视图的CGRect,如下所示: CGRect oldRect = [super thumbRectForBounds:bounds trackRect:rect value:value]; 然后,更改oldRect.x和oldRect.y,获取NewRect 最后一个,返回NewRect。