Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger a method in UIViewController from its View

I have a UIViewController with its UIView which contains a UIButton. I want to trigger a method in UIViewController on button click event.
Keeping reference of UIViewController doesn't seem to be a good idea like the following link says: Get to UIViewController from UIView?

So I want to achive this using a delegate. Any hint on how to achieve this?

like image 865
bhawesh Avatar asked Mar 12 '13 12:03

bhawesh


2 Answers

You can do something like this

CustomView.h

#import <UIKit/UIKit.h>
@protocol CustomViewDelegate <NSObject>

 -(void)didButtonPressed;

@end

 @interface CustomView : UIView

  @property (assign) id<CustomViewDelegate> delegate;

@end

CustomView.m

#import "CustomView.h"
@implementation CustomView

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    // Initialization code
    self.backgroundColor = [UIColor whiteColor];

    //[self addSubview:titleLbl];
    UIButton *button= [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(100, 100, 100, 50);
    [button addTarget:self.delegate action:@selector(didButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"pressMe" forState:UIControlStateNormal];
    [self addSubview:button];


}
return self;
}

in your ViewController.m

-(void)loadView
 {
  [super loadView];
  CustomView *view = [[CustomView alloc]initWithFrame:self.view.bounds];
  view.delegate = self;
  [self.view addSubview:view];

 }
like image 187
Anil Varghese Avatar answered Nov 14 '22 23:11

Anil Varghese


This is what the responder chain was built for. When you add a target to your button, just supply nil for the target:

[mySpecialButton addTarget:nil 
                 action:@selector(mySpecialButtonTapped:)
                 forControlEvents:UIControlEventTouchUpInside];

The nil target basically means "send mySpecialButtonTapped: to any object in the responder chain that can handle it".

Now you can handle this selector anywhere in the responder chain, which includes the button itself, its containing view, its containing view controller, the UIApplication, and finally your AppDelegate. Just place this method in the object most appropriate for your needs:

- (void)mySpecialButtonTapped:(id)sender {
    NSLog("My special button was tapped!");
}

You don't need delegates or callback blocks (as in the accepted answer) if you just want to bubble a message up.

like image 28
leftspin Avatar answered Nov 15 '22 01:11

leftspin