bha*_*esh 5 cocoa-touch uiviewcontroller ios
我有一个UIViewController包含它UIView的UIButton.我想UIViewController在按钮点击事件中触发一个方法.
保持参考UIViewController似乎不是一个好主意,如下面的链接说:
从UIView获取UIViewController?
所以我想使用委托来实现这个目标.有关如何实现这一点的任何提示?
你可以做这样的事情
CustomView.h
#import <UIKit/UIKit.h>
@protocol CustomViewDelegate <NSObject>
-(void)didButtonPressed;
@end
@interface CustomView : UIView
@property (assign) id<CustomViewDelegate> delegate;
@end
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
在您的ViewController.m中
-(void)loadView
{
[super loadView];
CustomView *view = [[CustomView alloc]initWithFrame:self.view.bounds];
view.delegate = self;
[self.view addSubview:view];
}
Run Code Online (Sandbox Code Playgroud)