iOS中block的使用分爲三個部分
1、第一部分聲明,定義和使用Block,
2、第二部分__block關鍵字的使用
3、第三部分:Block作爲property屬性實現頁面之間傳值
日常項目中使用最多的是block的反向傳值
這裏總結了一下block的普通傳值和在cell中的使用(經常用到)
1,普通的反向傳值
block三部曲
聲明:
@property (nonatomic,copy)void (^block) (NSString * text);
定義:
//結束編輯
-(void)textFieldDidEndEditing:(UITextField *)textField
{
//給block賦值
if (textField.text.length>0) {
self.block(textField.text);
[self.navigationControllerpopViewControllerAnimated:YES];
}
}
使用:
//點擊屏幕任一位置跳轉界面
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
SecondViewController*svc=[[SecondViewControlleralloc]init];
//取block的值
svc.block = ^(NSString * text){
self.navigationItem.title=text;
};
[self.navigationControllerpushViewController:svcanimated:YES];
}
這裏避免重複定義或者使用,否則會崩潰2 在cell中的使用
1>聲明:@property (strong,nonatomic)void (^didCollection)(LocationCityEntity *,NSIndexPath *);//傳模型和系統的NSIndexPath 方便使用組和行
2>在系統方法中定義
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
LocationCityEntity * entity =self.hotArray[indexPath.row];
if(self.didCollection){
self.didCollection(entity,indexPath);//賦值模型和系統indexPath
}
}
3>在CitySelectViewController cell中的實現使用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
if (tableView!=self.myTableView) {
staticNSString* cellId=@"cellId";
__weaktypeof(self) weakSelf=self;
myCell.didCollection=^(LocationCityEntity * entity,NSIndexPath *indexpa)
{
typeof(self) strongSelf=weakSelf;
NSString *msg = [NSStringstringWithFormat:@"切換地區將會登出當前賬號,是否要切換至%@站?",entity.zxprovince];
UIAlertView *alert =[[UIAlertViewalloc]initWithTitle:@"提示"message:msgdelegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"確定",nil];
alert.tag =indexpa.row;
strongSelf.isShow=NO;
[alert show];
};
cell = myCell;
}
}
return cell;
}
附件:地區篩選的demo(免積分下載),使用了block ,類擴展,本地保存等(只爲共同學習)
http://download.csdn.net/detail/bddzzw/9597894