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
注:委托方要采用弱引用。若采用强引用的话,就会导致循环引用,使得控制器和自定义控件都无法释放,程序奔溃。
相关文章推荐
- 解决用Ranorex安装app时报错
- [Beta阶段]展示博客
- 51nod1175
- 华为机试——约瑟夫环问题(总结)
- Ubuntu 关闭guest用户
- spring2.5.6的‘annotation-config’ and its parser class are only available on JDK 1.5 and higher错误解决
- web规范标准
- Mybatis/Ibatis,数据库操作的返回值
- VMware中的suse linux安装VMtools方法
- [转]常用Git命令清单
- hdu2665
- QT 编写Rtf(富文本格式) 文件实例
- 关于using声明与using指令 c++
- WebDriver工厂类封装
- Map集合视频学习
- 【c++】构造函数为什么不能是虚函数
- java并发库中的LockSupport介绍及使用
- 华为机试——自动售货机找零
- 大型网站系统架构演化之路
- 排序算法(二)之希尔排序、堆排序