ios 浅谈block的基本使用

栏目: IOS · 发布时间: 5年前

内容简介:block:我们称代码块,他类似一个方法。其实block也是一个数据类型,只是这个数据类型比较的特殊,是用来保存代码块的数据类型。快捷键:输入inlineBlock基本结构:

block:我们称代码块,他类似一个方法。其实block也是一个数据类型,只是这个数据类型比较的特殊,是用来保存代码块的数据类型。

快捷键:输入inlineBlock

<#returnType#>(^<#blockName#>)(<#parameterTypes#>) = ^(<#parameters#>) {
            <#statements#>
}

基本结构:

返回值类型(^block名字)(参数类型) =  ^返回值(参数类型 参数名 ){  

    如果block有返回值,一定要记得在block代码中返回值    
    但是申明中的返回值可以不写
 }  ;
//1.Block的参数是给Block代码块用的
//2.类型:返回值类型(^)(参数类型

常见的使用场景:

1.传递数据:把block当作参数去传值

2. 响应事件:(特殊的传递数据):当内部不确定外界做什么事情的时候可以搞一个block参数。

3.链式语法 :核心思想为将block作为方法的返回值,且返回值的类型为调用者本身,并将该方法以setter的形式返回,这样就可以实现了连续调用,即为链式编程。如Masonry框架(参考网络文档)

block简单的声明使用

ios 浅谈block的基本使用
简单的声明
ios 浅谈block的基本使用
ios 浅谈block的基本使用
使用较为复杂的block
实例:重写block动画
//view的动画实现,将不确定的事用block代替,此部分代码可以通过外界传入,交给使用者去处理。
+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations ;

[UIView animateWithDuration: <(NSTimeInterval)> animations: <^(void)animations>] ;
CGFloat duration = 0.5;
    void (^task)() = ^{
        
        self.redView.center = CGPointMake(300, 400);
        self.redView.bounds = CGRectMake(0, 0, 200, 200);
    };
    
    [self myAnimateWithDuration:duration animations:task completion:^{
        NSLog(@"动画完成");
    }];
    
}


- (void)myAnimateWithDuration:(CGFloat)duration  animations:(void(^)())anim completion:(void(^)())completionTask{
    
    self.completionTask = completionTask;
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:duration];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(stop)];
    
    //动画执行代理
    anim();
    
    [UIView commitAnimations];
}



//动画完成时调用
- (void)stop {
    
    self.completionTask();
}

在网上找了一写的比较好的关于block的文章,如果感兴趣可以点进去看看 https://www.jianshu.com/p/bcd494ba0e22

欢迎大家指正批评!

转载时请注明出处及相应链接,本文永久地址:https://blog.yayuanzi.com/24928.html

ios 浅谈block的基本使用

ios 浅谈block的基本使用 微信打赏

ios 浅谈block的基本使用 支付宝打赏

感谢您对作者Annwn的打赏,我们会更加努力!    如果您想成为作者,请点我


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pragmatic Thinking and Learning

Pragmatic Thinking and Learning

Andy Hunt / The Pragmatic Bookshelf / 2008 / USD 34.95

In this title: together we'll journey together through bits of cognitive and neuroscience, learning and behavioral theory; you'll discover some surprising aspects of how our brains work; and, see how ......一起来看看 《Pragmatic Thinking and Learning》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具