0

I'm trying to creating a custom UIView, lets call it FooView.

FooView.h

#import <UIKit/UIKit.h>

@interface FooView : UIView

@property (nonatomic, strong) UITextField *barTextField;
@property (nonatomic, strong) UIButton *submitButton;

@end

FooView.m

#import "FooView.h"

@implementation FooView

@synthesize barTextField = _barTextField;
@synthesize submitButton = _submitButton;

...

@end

FooViewController.h

#import <UIKit/UIKit.h>
#import "FooView.h"

@interface FooViewController : UIViewController

@property (nonatomic, strong) FooView *fooView;

@end

FooViewController.m

#import "SearchViewController.h"

@interface SearchViewController ()
@end

@implementation SearchViewController
@synthesize fooView = _fooView;

@end

I want the button touch event to be implemented in FooViewController, is delegate can achieve this? If YES, how?

Currently, I'm adding the touch event in such a way

FooViewController.m

- (void)viewDidLoad
{
    [self.fooView.submitButton addTarget:self action:@selector(submitTapped:) forControlEvents:UIControlEventTouchUpInside];
}

...
- (IBAction)submitTapped
{
    ...
}

But I don't think this is a good solution, so need some expert advice.

Any idea?

Js Lim
  • 3,625
  • 6
  • 42
  • 80

1 Answers1

3

Yes you can implement using delegate

FooView.h

#import <UIKit/UIKit.h>

@protocol FooViewDelegate
    -(void)submitButtonClicked:(id)sender;
@end

@interface FooView : UIView

@property (nonatomic, strong) UITextField *barTextField;
@property (nonatomic, strong) UIButton *submitButton;
@property (nonatomic, assign) id<FooViewDelegate> delegate;

@end

FooView.m

#import "FooView.h"

@implementation FooView

@synthesize barTextField = _barTextField;
@synthesize submitButton = _submitButton;
@synthesize delegate;
...

-(IBAction)buttonClicked:(id)sender // connect this method with your button
{
    [self.delegate submitButtonClicked:sender];
}

@end

FooViewController.h

#import <UIKit/UIKit.h>
#import "FooView.h"

@interface FooViewController : UIViewController <FooViewDelegate>

@property (nonatomic, strong) FooView *fooView;

@end

FooViewController.m

#import "FooViewController.h"

@interface FooViewController ()
@end

@implementation FooViewController
@synthesize fooView = _fooView;

- (void)viewDidLoad
{
    _fooView = [[UIView alloc] init];
    _fooView.delegate = self;
}

-(void)submitButtonClicked:(id)sender //delegate method implementation
{
    NSLog(@"%@",[sender tag]);
}

@end
βhargavḯ
  • 9,786
  • 1
  • 37
  • 59
  • Is that a good idea though ? Isn't it breaking MVC principles since you are having a view performing a controller action - or is it just setting a bit more memory for delegate and chaining it all back to the controller (viewcontroller) ? – Petar Dec 02 '14 at 21:57