您的位置:首页 > 其它

ViewController之间的block传值

2015-08-27 18:05 225 查看

两个界面ViewController之间的block传值

槽点:做了类似于知乎和新浪微博@用户,搜索用户名,跳转回评论页面,textView获取搜索结果的用户,需要用到的是反向传值使用block的一点小功能就可以实现。

用语言叙述是这样的:第一个界面[b]A有一个textView,第二个界面B是一个搜索搜索功能界面,点击搜索结果的cell,第二个界面B消失并把cell上的用户名显示到第一个界面A的textView里面,区别字体颜色[/b]

在B界面定义声明Block属性

//定义block
typedef void (^PointNameBlock)(NSString *pointName);//声明定义一个名字为PointNameBlock的Block

@interface BViewController : UIViewController
/**
 *  @用户的回调block
 */
@property(nonatomic,copy)PointNameBlock pointNameBlock;//顶一个类型为PointNameBlock的属性
/**
 *  回调block 方法
 *
 *  @param block
 */
-(void)returnPointName:(PointNameBlock)block;//定义一个回调Block的方法


在B界面需要做的是给通过这个Block回调方法把需要传递的值传递过去

#pragma mark - block 代理方法
-(void)returnPointName:(PointNameBlock)block{
    self.pointNameBlock=block;
}


根据我的项目需求,我是点击搜索结果的cell,界面B消息 把cell的Lable.text传给上个界面

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

if (self.pointNameBlock !=nil) {

    self.pointNameBlock([NSString stringWithFormat:@"@%@",self.nameArray[indexPath.row][@"name"]]);

    [self.navigationController popViewControllerAnimated:YES];

  }
}


在A界面获取B界面的时,B界面对象调用block方法完成block传值

SearchUserNameViewController *searchUserNameView=[[SearchUserNameViewController alloc]init];

[searchUserNameView returnPointName:^(NSString *pointName) {

    _commentTextView.text=[NSString stringWithFormat:@"%@%@ ",_commentTextView.text,pointName];

    NSMutableAttributedString *attribute=[[NSMutableAttributedString alloc]initWithString:_commentTextView.text];
     //这里可以根据项目需求设置字体的大小和颜色区分 @用户名

    _commentTextView.attributedText=attribute;

}];
[self.navigationController pushViewController:searchUserNameView animated:YES];


大自然的搬运工,在传值这块也是搜了一些其他人的方法,觉得这样是比较方便,代码量也比较少!借项目代码做下笔记^_^
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: