您的位置:首页 > 其它

192,自定义代理delegate

2016-01-10 14:15 253 查看






AppView.h:

#import <UIKit/UIKit.h>

@class AppView;

// 1. 协议名以类名开始+Delegate

@protocol AppViewDelegate <NSObject>

// 2. 协议方法,以类名开始(没有类前缀),第一个参数是自己

// 只是定义方法名,不做具体实现

@optional

-(void)appViewDidShowDialog:(AppView *) appView;

@end

@interface AppView :
UIView

// 3. 定义代理属性,遵守了AppViewDelegate协议的任意一个对象,都可以成为代理

@property(nonatomic,weak)id<AppViewDelegate> delegate;

@property(nonatomic,strong)NSString *name;

@end

AppView.m:

#import "AppView.h"

@implementation AppView

- (IBAction)showDialog:(UIButton *)sender {

//4,检测是否实现了该方法

if ([self.delegaterespondsToSelector:@selector(appViewDidShowDialog:)]) {

self.name =@"ljs";

[self.delegateappViewDidShowDialog:self];

}

}

@end

ViewController.m:

#import "ViewController.h"

#import "AppView.h"

@interface
ViewController () <AppViewDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {

[superviewDidLoad];

AppView *appView = [[[NSBundlemainBundle]
loadNibNamed:@"AppView"owner:niloptions:nil]lastObject];

//5,设置代理的值

appView.delegate =
self;

[self.viewaddSubview:appView];

}

//6,执行代理方法

-(void)appViewDidShowDialog:(AppView *)appView{

NSString *str = [NSStringstringWithFormat:@"你好!%@",appView.name];

UIAlertController *alertController = [UIAlertControlleralertControllerWithTitle:@"问候语"message:str
preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *confirm = [UIAlertActionactionWithTitle:@"确定"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction
*_Nonnull action) {

}];

[alertController addAction:confirm];

[selfpresentViewController:alertController
animated:YEScompletion:^{

}];

}

@end

注:委托方要采用弱引用。若采用强引用的话,就会导致循环引用,使得控制器和自定义控件都无法释放,程序奔溃。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: