iOS - 带触摸事件的自定义视图

时间:2013-03-12 03:40:51

标签: ios delegates touch-event custom-view

我正在尝试创建自定义UIView,我们称之为 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

我希望按钮触摸事件在 FooViewController 中实现,delegate是否可以实现此目的?如果,怎么做?

目前,我正在以这种方式添加触摸事件

FooViewController.m

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

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

但我不认为这是一个很好的解决方案,所以需要一些专家建议。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

是的,您可以使用委托

实施

<强> 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