简体   繁体   中英

UISlider subclass for custom thumb location and thumb image?

在此处输入图片说明

Is it possible to implement above slider by subclassing UISlider? I want slider thumb move to edges but there is some space left. I have achieved custom position by overriding following methods but now thumb is not responding to touch events.

-(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);
}

I implemented above by subclassing UISlider and for touch event issue I added height constraint to slider in storyboard to increase bounds at runtime. Following is the code to move slider to edges and custom thumb location:

//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);
}

I think the code is wrong. First, you should get the CGRect of the custom view like this: CGRect oldRect = [super thumbRectForBounds:bounds trackRect:rect value:value]; Than, change the oldRect.x and oldRect.y ,get NewRect The last , return the NewRect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM