Search code examples
iosobjective-cxcodeuislider

UISlider Constraints Programmatically: "Constraint items must each be an instance of UIView or subclass"


My constraints are causing my app to crash due to them not being an instance of UIView. However, they are instances of UIView, at least to my knowledge. My goal is to attach this slider to the toolbar as a UIBarbuttonItem. Here is what I have in viewDidLoad:

// Slider Implementation
slider_textSize.minimumValue = 9;
slider_textSize.maximumValue = 72;
slider_textSize.value = 12;
slider_textSize.continuous = YES;

[self.view setUserInteractionEnabled:YES];
[self.view addSubview:self.slider_textSize];

self.slider_textSize.translatesAutoresizingMaskIntoConstraints = NO;

[self.view addConstraint:[NSLayoutConstraint
                          constraintWithItem:self.slider_textSize
                          attribute:NSLayoutAttributeLeft
                          relatedBy:NSLayoutRelationEqual
                          toItem:self.view
                          attribute:NSLayoutAttributeLeft
                          multiplier:1
                          constant:5]];

[self.view addConstraint:[NSLayoutConstraint
                          constraintWithItem:self.slider_textSize
                          attribute:NSLayoutAttributeRight
                          relatedBy:NSLayoutRelationEqual
                          toItem:button_done attribute:NSLayoutAttributeRight
                          multiplier:1
                          constant:10]];

"slider_textSize" is a strong, nonatomic property of this class and implemented in my initializer like so:

[slider_textSize addTarget:self
                 action:@selector(slider_textSizeValueChanged:)
                 forControlEvents:UIControlEventValueChanged];

I've been using the answer from this question, but it doesn't seem to be working for me. This is the error I get exactly:

2015-03-06 10:26:08.300 rED[14238:3168995] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]: Constraint items must each be an instance of UIView or subclass'

I've tried everything I could with no luck. Any ideas? Thanks in advance!


Solution

  • I ended up ditching the constraints since they became too complicated with bar button items. Instead, I made the width of the slider a proportion to the width of the screen.

        CGRect screenRect = [[UIScreen mainScreen] bounds];
        CGFloat screenWidth = screenRect.size.width;
        CGFloat screenHeight = screenRect.size.height;
    
        CGFloat sliderWidth = .786 * screenWidth;
        CGRect frame = CGRectMake(0, 0, sliderWidth, 32);
        slider_textSize = [[UISlider alloc] initWithFrame:frame];