標籤:android style color 檔案 for io
定義block和定義delegate一樣,都是在得到需要的值那個頁面的類裡定義。
eg:A類、B類,我要將A類中的值傳給B類,那麼我就到A類中定義block,B類取值就可以了。。。。
For example:
第一步:
A類中:
.h檔案:
#import "BaseViewController.h"
//定義塊
typedef void (^addCommunity)(UIImage *img,NSString *title);
@interface MoreViewController : BaseViewController
@property(nonatomic,copy)addCommunity adds;
-(void)addCommunityWithBlock:(addCommunity)addBlock;
.m檔案:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
imgView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
NSString *img = @"market-android.png";
imgView.image = [UIImage imageNamed:img];
[self.view addSubview:imgView];
lblTitle = [[UILabel alloc]initWithFrame:CGRectMake(135, 230, 100, 30)];
lblTitle.text = @"標題";
lblTitle.textColor = [UIColor redColor];
[self.view addSubview:lblTitle];
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 300, 100, 30)];
[btn setTitle:@"添加" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];
[btn setBackgroundColor:[UIColor redColor]];
[self.view addSubview:btn];
}
-(void)add{
_adds(imgView.image,lblTitle.text); //block傳值
[self.navigationController popToRootViewControllerAnimated:YES];
}
-(void)addCommunityWithBlock:(addCommunity)addBlock{
_adds = addBlock;
}
第二步:
B類中:
.m檔案:
[more addCommunityWithBlock:^(UIImage *img,NSString *title){
NSDictionary *dic = [NSDictionary dictionaryWithObject:img forKey:title];
}];
在你需要用到值的地方,調用block,說明:more是A類的一個別名。這樣就把B頁面的值傳到了A頁面的NSDictionary中。。。。。。。我覺得寫得還算清楚吧!嘿嘿......