简体   繁体   中英

UIButton target to be UIViewController not custom UIView

I have a UIViewController which creates a custom sub view. The sub view is a UIView object which has been subclassed a few times.

Within the subview class I create a custom init method:

-(id)init {
    self = [super init];
    if (self) {
        // Init code
        [self spm_correctGuessViewCustomInit];
    }
    return self;
}

And within this I create a button and a label. The question relates directly to the button and its target action.

What I would like is for the UIViewController to have the buttons action, not the subclasses UIView (which actually creates and holds the button).

[continueButton addTarget:self.superview action:@selector(correctGuessContinueButtonPressed) forControlEvents:UIControlEventTouchUpInside];

I pass in the target of self.superview, this appears to work correctly and the correct method is run. However, I am shown a warning in the subclass 'Undeclared selector 'correctGuessContinueButtonPressed''

So am I implementing this approach correctly? Please let me know if more information is required.

Your view.superview approach will not bring you to the view controller, but to a view.

You can import the header of your implementing class to fix the warning, but I think your design should be improved. Views should work pretty much on their own and not depend on their superviews, or even worse the whole architecture of views and controllers.

I'd pass a delegate down the line that gets called when the user pressed the button, or set some blocks on the views that get called when buttons fire.

Avoid communication over several layers of abstraction.

One solution would be to update your custom view's init method so it takes target and action parameters (much like the addTarget: method of the button). You could then pass these values to the button via the addTarget: call.

- (instancetype)initWithTarget:(id)target action:(SEL)action {
    // your normal init code here
    // use target and action to setup your button
}

Reference previous similar question: Calling a method in a UIViewController from a UIButton in a subview

  1. I had to add an import to the View Controller that the method was on, within the custom UIView subclass.

  2. With the controller property set I could set the button target as controller

  3. Ensure that the method that was being called from the button was in the controller header file, so could be seen by the subview implementation file. Previously this was not so the subview was not to know this existed.

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