兩個界面ViewController之間的block傳值
槽點:做了類似於知乎和新浪微博@用戶,搜索用戶名,跳轉回評論頁面,textView獲取搜索結果的用戶,需要用到的是反向傳值使用block的一點小功能就可以實現。
用語言敘述是這樣的:第一個界面A有一個textView,第二個界面B是一個搜索搜索功能界面,點擊搜索結果的cell,第二個界面B消失並把cell上的用戶名顯示到第一個界面A的textView裏面,區別字體顏色
在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];
大自然的搬運工,在傳值這塊也是搜了一些其他人的方法,覺得這樣是比較方便,代碼量也比較少!借項目代碼做下筆記^_^