配有Block的UIButton类替代选择 – UIButton-Bloc...

codeday· 2019-09-23
本文来自 codeday ,作者 codeday

UIButton-Blocks

一个UIButton类的替代选择,配有Block.

特性

  • block 语法

安装

Cocoapods(推荐)

  1. 在Podfile中添加pod ‘UIButton+Blocks’
  2. 运行pod install

手动

  1. 将UIButton+Blocks/UIButton+Blocks中的所有文件添加到项目中

需求

  • iOS 5.0 +
  • ARC/MRC

示例

Code:

Objective-C

UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake((MDScreenWidth-100)*0.5, (MDScreenHeight-100)*0.5, 100, 100);
    [self.view addSubview:button];
    
    button.backgroundColor = [[UIColor orangeColor] colorWithAlphaComponent:0.8];
    [button setTitle:@"Blocks" forState:UIControlStateNormal];

    //default UIControlEventTouchUpInside
    [button handleClickWithClickBlock:^(UIButton *sender) {
        NSLog(@"%s",__func__);

    }];
    
    
    /*
     [button handleClickEvent:UIControlEventTouchUpInside withClickBlock:^(UIButton *sender) {
     NSLog(@"%s",__func__);
     }];
     */

Swift

在Swift项目中使用UIButton+Blocks需要:

  1. 将相关.m 和 .h 文件从UIButton+Blocks 文件夹复制到项目中
  2. 如果提示创建”bridging header”,那么请创建。如果没有提示并且如果你们有一个桥接头,请创建一个。?

下一步

  1. 在桥接头添加代码:
#import "UIButton+Blocks.h"

做完上面的步骤之后你可以使用UIButton+Blocks编写Swift代码,例如,在Swift 3.0中:

let btn = UIButton(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 100, height: 100)))
     btn.center = view.center
     btn.backgroundColor = UIColor.purple
     btn.setTitle("SwiftVC", for: UIControlState.normal)
     view.addSubview(btn)
     
     btn.handleClick { (btn:UIButton?) in
         print("\("SwiftViewController") \(#function)")
         
     }