0

I've got a subclass of UISlider hooked up to a storyboard for valueChanged:

- (IBAction)valueChanged:(RSSlider*)slider {
    // do some super cool stuff with my new value
}

And in my subclass viewDidLoad, I've got:

UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sliderTapped:)];
[self addGestureRecognizer:gestureRecognizer];

And then in that same subclass, a nice tap handler that moves the slider along and updates the current value:

- (void)sliderTapped:(UIGestureRecognizer *)tap
{
    if (self.highlighted)
        return;
    CGPoint locationInView = [tap locationInView: self];
    CGFloat percentage = locationInView.x / self.bounds.size.width;
    CGFloat delta = percentage * (self.maximumValue - self.minimumValue);
    CGFloat value = self.minimumValue + delta;
    [self setValue:value];
}

That's all OK, the value gets set, and life goes on. Only problem though, is that my Storyboard handler in the view controller (we'll call it a delegate, though clearly it's not really) never gets called.

How can I trigger an update to the handler method once the value has been changed via tap?

1 Answer 1

1

Well as you mentioned, one way to handle this is through delegates.

Since the UISlider does not have a pre-defined delegate method for changing the value, you can make your own protocol in your subclass. Have your View Controller conform to that protocol, and call its methods via the delegate property.

Here is an example protocol and delegate creation:

@protocol RSSliderDelegate
- (void)changeValue:(RSSlider*)slider;
@end

@interface RSSlider: UISlider

@property (nonatomic, assign) id<RSSliderDelegate> delegate;

Then set your VC to conform to the protocol:

@interface ViewController : UIViewController <RSSliderDelegate>

Then simply set it when you create your slider:

RSSlider* rs = [[RSSlider alloc] init];
[rs setDelegate: self];

Implement the method:

- (void)changeValue:(RSSlider*)slider
{
    //Do some cool stuff
}

Finally, call the method from the subclass itself:

[self.delegate changeValue:self];
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.