使用委托——delegate进行参数传递

来源:互联网 发布:php curl 发送get请求 编辑:程序博客网 时间:2024/05/22 13:35

</pre><p></p><p><span style="font-size:14px"><span style="color:rgb(51,51,51); font-family:Arial; line-height:26px">在不同的视图控制器viewcontroller之间传递重要的参数,一种简单的方法就是通过委托——delegate</span></span></p><p><span style="font-family:Arial; color:#333333"><span style="line-height:26px"><span style="font-size:14px">首先我们有两个viewvontroller,一个为父viewcontroller:A,一个为子viewcontroller:B</span></span></span></p><p><span style="font-family:Arial; color:#333333"><span style="line-height:26px"><span style="font-size:14px">我们需要把 B中的数据传递给A, 实现方法如下:</span></span></span></p><p><span style="font-size:14px"></span></p><p><span style="color:rgb(51,51,51); line-height:19px"><span style="font-family:Verdana,Geneva,Arial,Helvetica,sans-serif"><span style="font-size:14px">1. 首先,在B.h中定义一个delegate:</span></span></span></p><p><span style="color:rgb(51,51,51); line-height:19px"><span style="font-size:14px"><span style="font-family:Verdana,Geneva,Arial,Helvetica,sans-serif"></span></span></span></p><pre name="code" class="cpp">@protocol ViewDelegate <NSObject>@required- (void)tapAction:(int)tag;@end

2.在B的头文件B.h里,声明delegate:

@property (nonatomic, assign) id<ViewDelegate> delegate;</span>

3.在B.m中实现delegate:

- (void)set:(UIButton *)button{    if ([self.delegate respondsToSelector:@selector(tapAction:)]) <span style="font-family: Arial, Helvetica, sans-serif;">{</span>
        [self.delegate tapAction:self.number];    }}


4.在A.h中添加delegate:

@interface AViewController ()<ViewDelegate>@end


5.B.m实现

- (void)tapAction:(int)tag{    NSString *title = [NSString stringWithFormat:@"%d",tag];    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];    [alertView show];}






0 0
原创粉丝点击