iOS开发丨使用闭包Block来进行初始化

在iOS开发中,闭包也就是Block是一种常用的特殊类型,可以正常定义变量、作为参数、作为返回值,还可以声明赋值去保存一段代码,在需要调用的地方去调用,目前Block已经广泛应用于各类回调传值、排序遍历、GCD、动画等。

下面,介绍一种比较冷门的使用闭包来进行初始化的例子,好处是在需要生成多个相同实例的时候会比较方便,代码上看着也比较整齐和清晰。

传统写法:

UILabel *titleLabel = [[UILabel alloc] init];
titleLabel.font = [UIFont systemFontOfSize:17 weight:UIFontWeightRegular];
titleLabel.textColor = [UIColor blackColor];
titleLabel.textAlignment = NSTextAlignmentCenter;
titleLabel.frame = CGRectMake(15, 15, 200, 30);
titleLabel.text = @"我是标题";
[self.view addSubview:titleLabel];

UILabel *textLabel = [[UILabel alloc] init];
textLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
textLabel.textColor = [UIColor blackColor];
textLabel.textAlignment = NSTextAlignmentCenter;
textLabel.frame = CGRectMake(15, 60, 200, 30);
textLabel.text = @"我是文本";
[self.view addSubview:textLabel];

闭包写法:

UILabel *titleLabel = ^{
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:17 weight:UIFontWeightRegular];
    label.textColor = [UIColor blackColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.frame = CGRectMake(15, 15, 200, 30);
    label.text = @"我是标题";
    return label;
}();
[self.view addSubview:titleLabel];

UILabel *textLabel = ^{
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    label.textColor = [UIColor blackColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.frame = CGRectMake(15, 60, 200, 30);
    label.text = @"我是文本";
    return label;
}();
[self.view addSubview:textLabel];

或者:

UILabel *(^newLabel)(NSString*, CGFloat) = ^(NSString *text, CGFloat fontSize) {
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:fontSize weight:UIFontWeightRegular];
    label.textColor = [UIColor blackColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = text;
    return label;
};

UILabel *titleLabel = newLabel(@"我是标题", 17);
titleLabel.frame = CGRectMake(15, 15, 200, 30);
[self.view addSubview:titleLabel];

UILabel *textLabel = newLabel(@"我是文本", 15);
textLabel.frame = CGRectMake(15, 60, 200, 30);
[self.view addSubview:textLabel];

你可能感兴趣的:(iOS开发丨使用闭包Block来进行初始化)