• 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];
    }
  • 相关阅读:
    viewport
    Flex 布局教程
    鼠标放上去盒子向上滑动
    鼠标放图片上,原图上划上去一个透明图片
    类加载过程
    JVM入门
    redis简介和安装
    JMH和Disruport
    线程池
    JUC
  • 原文地址:https://www.cnblogs.com/NFli/p/4399240.html
Copyright © 2020-2023  润新知