• iOS开发之block


    iOS开发之block

    1.什么是block,block的作用

    block      代码块,解决回调,理解为“匿名函数”,定义在方法里面(先定义,再使用)

    2.block的基本使用(语法)

    3.block在开发中的应用

    在A、B两个界面之间传值,改变背景颜色

    A界面

    #import "SecondViewController.h"
    
    @interface SecondViewController ()
    {
        //定义block变量,为了保存传人的参数
        void (^_action)(NSString *color);
    }
    @end
    
    @implementation SecondViewController
    
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    {
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (self) {
            // Custom initialization
        }
        return self;
    }
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
        
        self.view.backgroundColor = [UIColor brownColor];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(100, 200, 100, 30);
        [button setTitle:@"切换" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        
        
    }
    -(void)btnClick:(UIButton *)button
    {
        
        if (_action) {
            _action(@"blue");
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    -(void)setChangeBackgroundColor:(void (^)(NSString *))action
    {
        _action = action;
    }

    B界面

    -(void)createView
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(100, 200, 100, 30);
        [button setTitle:@"切换" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        
        
    }
    -(void)btnClick:(UIButton *)button
    {
        
        
        
        SecondViewController *svc = [[SecondViewController alloc] init];
        
        [svc setChangeBackgroundColor:^(NSString *color) {
            if ([color isEqualToString:@"blue"]) {
                self.view.backgroundColor = [UIColor blueColor];
            }
        }];
        
        [self presentViewController:svc animated:YES completion:nil];
    }
  • 相关阅读:
    【BZOJ2749】【HAOI2012】外星人[欧拉函数]
    【BZOJ3675】【APIO2014】序列分割 [斜率优化DP]
    【BZOJ2326】【HNOI2011】数学作业 [矩阵乘法][DP]
    【BZOJ1996】【HNOI2010】合唱队 [区间DP]
    【BZOJ1857】【SCOI2010】传送带 [三分]
    【BZOJ2338】【HNOI2011】数矩形 [计算几何]
    【BZOJ2330】【SCOI2011】糖果 [差分约束]
    【BZOJ1095】【ZJOI2007】捉迷藏 [动态点分治]
    【BZOJ4031】【HEOI2015】小Z的房间 [Matrix-Tree][行列式]
    【FJWC2017】交错和查询 [线段树]
  • 原文地址:https://www.cnblogs.com/NFli/p/4399240.html
Copyright © 2020-2023  润新知