要求:在一个UIView界面中又一个lable和Button,想点击按钮之后改变lable的值,用协议委托实现
Protocol(ChangeText.h):
#import <Foundation/Foundation.h> @protocol ChangeText <NSObject> -(void)change:(NSString *)val; @end
Button.h:
#import <Foundation/Foundation.h> #import "ChangeText.h" @interface Button : NSObject @property(nonatomic,retain) id<ChangeText> delegate; -(void)changetext:(NSString *)str; @end
Button.m:
#import "Button.h" @implementation Button -(void)changetext:(NSString *)val { if ([_delegate respondsToSelector:@selector(change:)]) { [_delegate change:val]; } } - (void)dealloc { [_delegate release]; [super dealloc]; } @end
创建一个遵循协议的View
ViewA.h:
#import <Foundation/Foundation.h> #import "ChangeText.h" #import "Button.h" @interface ViewA : NSObject<ChangeText> @property(nonatomic,retain)NSString* textValue; @property(nonatomic,retain)Button *btn; //实现协议的change方法 -(void)change; @end
View.m:
#import "ViewA.h" @implementation ViewA +viewAWithText:(NSString *)val { ViewA *a = [[[ViewA alloc] init] autorelease]; a.textValue = @"text"; //初始化Button,并且将当前实现了协议的ViewA赋给button他的委托方法 Button *btn = [[[Button alloc] init] autorelease]; btn.delegate = a; a.btn = btn; return a; } -(void)change:(NSString *)val { self.textValue = val; NSLog(@"当前的view中文本值是:%@",self.textValue); } -(void)dealloc { [_btn release]; [_textValue release]; [super dealloc]; } @end
main:
#import <Foundation/Foundation.h> #import "ViewA.h" #import "Button.h" int main(int argc, const char * argv[]) { @autoreleasepool { ViewA *view = [ViewA viewAWithText:@"text"]; NSLog(@"当然view中的文本值是:%@",view.textValue); [view.btn changetext:@"lable"]; } return 0; }
结果:
2013-08-05 17:23:22.754 按钮点击[2144:303] 当然view中的文本值是:text
2013-08-05 17:23:22.756 按钮点击[2144:303] 当前的view中文本值是:lable
本文转自蓬莱仙羽51CTO博客,原文链接:http://blog.51cto.com/dingxiaowei/1366464,如需转载请自行联系原作者