Protocol 模拟UI中一个按钮点击改变lable中的值

简介:

要求:在一个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,如需转载请自行联系原作者

相关文章
如何实现 CRM Attachment UI 的 Advanced 按钮
如何实现 CRM Attachment UI 的 Advanced 按钮
|
3月前
|
JavaScript
Vue给Element UI的el-popconfirm绑定按钮事件
Vue给Element UI的el-popconfirm绑定按钮事件
|
5天前
|
图形学
小功能⭐️Unity获取点击到的UI
小功能⭐️Unity获取点击到的UI
|
2月前
|
XML IDE 开发工具
【Android UI】自定义带按钮的标题栏
【Android UI】自定义带按钮的标题栏
39 7
【Android UI】自定义带按钮的标题栏
|
1月前
|
JavaScript API
【Element-UI】vue使用 this.$confirm区分取消与关闭,vue给this.$confirm设置多个按钮
【Element-UI】vue使用 this.$confirm区分取消与关闭,vue给this.$confirm设置多个按钮
66 0
|
1月前
|
开发者
小而美的IKUN-UI组件库源码学习(按钮 Button)
小而美的IKUN-UI组件库源码学习(按钮 Button)
9 0
|
3月前
【UI】elementui select点击获取label 和 value
【UI】elementui select点击获取label 和 value
23 1
|
3月前
|
算法 API 开发者
【Qt UI相关】Qt中如何控制 窗口的最大化、最小化和关闭按钮?一文带你掌握用法
【Qt UI相关】Qt中如何控制 窗口的最大化、最小化和关闭按钮?一文带你掌握用法
628 1
|
3月前
|
前端开发 搜索推荐 开发者
SAP UI5 sap.m.Column 控件的 minScreenWidth 属性介绍
SAP UI5 sap.m.Column 控件的 minScreenWidth 属性介绍
|
3月前
|
JavaScript 前端开发 开发者
SAP UI5 控件 sap.m.ListBase 的 inset 属性的作用介绍
SAP UI5 控件 sap.m.ListBase 的 inset 属性的作用介绍