我使用OC来自定义工具类,创建按钮工具,如何将此工具转换为swift代码?在行_buttonBlock = [button copy];
中如何在swift中复制用户?
ToolView .h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface ToolView : NSObject
+ (instancetype)shendInstance;
- (void)createButtonWithFrame:(CGRect)rect superView:(UIView *)superView buttonBlock:(void(^)(UIButton *button))button;
@end
ToolView.m
#import "ToolView.h"
typedef void(^ButtonBlock)();
@interface ToolView(){
ButtonBlock _buttonBlock;
}
@end
@implementation ToolView
+ (instancetype)shendInstance{
static ToolView *toolview = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
toolview = [[ToolView alloc]init];
});
return toolview;
}
- (void)createButtonWithFrame:(CGRect)rect superView:(UIView *)superView buttonBlock:(void(^)(UIButton *button))button{
_buttonBlock = [button copy];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = rect;
btn.backgroundColor = [UIColor orangeColor];
[btn addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[superView addSubview:btn];
}
- (void)buttonAction:(UIButton *)sender{
if (_buttonBlock) {
_buttonBlock(sender);
}
}
@end
答案 0 :(得分:0)
在行_buttonBlock = [按钮复制];如何在swift中复制用户?
您不要在Swift中复制块参数,而是将参数标记为转义。你的Swift函数将被声明为:
fun createButton(frame: CGRect,
superView: UIView,
buttonBlock: @escaping (UIButton) -> Void
)
请参阅The Swift Programming Language: Closures中的转义闭包。
答案 1 :(得分:-1)
我转换了它,我自己的代码如下:
ToolView.swift
import UIKit
class ToolView: NSObject {
static let instance: ToolView = ToolView()
class func shareInstance() -> ToolView{
return instance
}
var blockActionBlock:((UIButton) -> Void)?
func createButton(frame: CGRect, superView: UIView, buttonBlock: @escaping (UIButton) ->Void) -> Void { //
let button = UIButton()
button.frame = frame
button.backgroundColor = UIColor.red
superView .addSubview(button)
button .addTarget(self, action: #selector(self.buttonAction), for: UIControlEvents.touchUpInside)
blockActionBlock = buttonBlock
}
@objc func buttonAction(sender: UIButton){
blockActionBlock!(sender)
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
ToolView .shareInstance().createButton(frame: CGRect(x:100, y: 100, width:100, height:50), superView: self.view) { (button) in
print("Click Button \(button)")
}
}
}