0

I'm attempting to implement the target-action pattern in a custom UIControl. Here's the setup:

// Inside custom UIControl class

- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
    ...

    // UIControl method to update targets when values change
    [self sendActionsForControlEvents:UIControlEventValueChanged];

    return YES;
}

- (void)valueChanged:(id)control
{
    NSLog(@"Value changed");
}

I have a simple view controller that initializes an instance of my custom UIControl and registers as a target for when values change:

// Inside view controller

@implementation HKViewController
{
    HKCustomControl *_customControl;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    _customControl = [[HKCustomControl alloc]];

    [self.view addSubview:_customControl];

    [_customControl addTarget:self
                action:@selector(valueChanged:)
      forControlEvents:UIControlEventValueChanged];
}

The error I get is: ''NSInvalidArgumentException', reason: '-[HKViewController valueChanged:]: unrecognized selector sent to instance 0x16d95b20'

I have added - (void)valueChange:(id)control to the .h file for my custom control as well.

I have read a number of posts already about similar errors but none specific to this pattern. I could use a second pair of eyes to see where I'm going wrong.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
H K
  • 1,215
  • 2
  • 16
  • 29

2 Answers2

0

action is sent to object specified in addTarget which is self as per your following statement:

[_customControl addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];

So you need to add the valueChanged to controller class object.

JamesWebbTelescopeAlien
  • 3,547
  • 2
  • 30
  • 51
  • Why would you do this? This means the control responds to its own changes. The need is for the view controller to know about the changes. – rmaddy Jan 23 '15 at 22:07
  • @maddy idea was to emphasize on the fact the `valueChanged:` should be defined in the class specified in `addTarget`. – JamesWebbTelescopeAlien Jan 24 '15 at 01:18
0

Answer was provided by @rmaddy: I needed to have the valueChanged: method in the view controller instead of the class

H K
  • 1,215
  • 2
  • 16
  • 29