Search code examples
iosobjective-cuislider

UISlider crashes app when adding programmatically to view


I have a custom overlay for camera, it that overlay I have UISlider:

@implementation LWOverlayView

- (id)initWithFrame:(CGRect)frame imagePath:(NSString*) imagepath{
    if ((self = [super initWithFrame:frame])) {
        // Clear the background of the overlay:
        self.opaque = NO;
        self.backgroundColor = [UIColor clearColor];


        UIImageView *overlayGraphicView = [[UIImageView alloc] init];
        overlayGraphicView.contentMode = UIViewContentModeScaleAspectFill;
        [overlayGraphicView setImageWithURL:[NSURL URLWithString:imagepath]
                       placeholderImage:[UIImage imageNamed:@"placeholder.png"]];


        overlayGraphicView.frame = CGRectMake(80, 140, 160, 120);
        [self addSubview:overlayGraphicView];

        UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 436, 320, 44)];
        [toolbar setBarStyle:UIBarStyleBlackOpaque];

        UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismiss)];

        CGRect frame = CGRectMake(0.0, 0.0, 200.0, 10.0);
        UISlider *slider = [[UISlider alloc] initWithFrame:frame];
        [slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
        [slider setBackgroundColor:[UIColor clearColor]];
        slider.minimumValue = 0.0;
        slider.maximumValue = 50.0;
        slider.continuous = YES;
        slider.value = 25.0;


        [toolbar setItems:[NSArray arrayWithObjects:doneButton, slider, nil]];

        [self addSubview:toolbar];

    }
    return self;
}

App crashes:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UISlider view]: unrecognized selector sent to instance 0x20854fe0'

Any hints?


Solution

  • As has been pointed out, you can't directly add a UISlider (or any other UIView) directly to the list of toolbar items.

    What you need to do is create a UIBarButtonItem that contains the slider.

    UIBarButtonItem *sliderBtn = [[UIBarButtonItem alloc] initWithCustonView:slider];
    

    Now add sliderBtn to the array instead of slider.

    You may find you need to set the width property on sliderBtn.