歡迎加入QQ討論群258996829
J_K_D 頭像
蘋果0袋
0
J_K_D

關(guān)于用柯里化實(shí)現(xiàn)Target-Action的疑問

發(fā)布時(shí)間:2017-10-05 15:53  回復(fù):0  查看:4069   最后回復(fù):2017-10-05 15:53  
在看了喵神的書籍后,一直有個(gè)疑問,就是里面說到的使用swift的柯里化來封裝Target-Action模式。先上代碼( 代碼中稍微有改動(dòng),我將Control繼承了UIButton):

protocol TargetAction {

    func performAction()

}



struct TargetActionWrapper<T: AnyObject> : TargetAction {

    weak var target: T?

    let action: (T) -> () -> ()

    

    func performAction() -> () {

        if let t = target {

            action(t)()

        }

    }

}



enum ControlEvent {

    case TouchUpInside

    case ValueChanged

    // ...

}



class Control : UIButton{

    var actions = [ControlEvent: TargetAction]()

    

    func setTarget<T: AnyObject>(target: T, action: @escaping (T) -> () -> (), controlEvent: ControlEvent) {

        actions[controlEvent] = TargetActionWrapper(target: target, action: action)

    }

    

    func removeTargetForControlEvent(controlEvent: ControlEvent) {

        actions[controlEvent] = nil

    }

    

    func performActionForControlEvent(controlEvent: ControlEvent) {

        actions[controlEvent]?.performAction()

    }

}


然后查了原本出自的博客文,說是這樣使用 
class MyViewController {

    let button = Control()

    

    func viewDidLoad() {

        button.setTarget(target: self, action: MyViewController.onButtonTap, controlEvent: .TouchUpInside)

    }

    

    func onButtonTap() {

        print("Button was tapped")

    }

}

  然后我就發(fā)現(xiàn),onButtonTap這個(gè)方法是沒辦法觸發(fā)的,除非,我自己給button添加一個(gè)target-action,然后在自己綁定的Action里 面條用performActionForControlEvent方法。代碼如下:
class ViewController: UIViewController {

    let button = Control.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 40))

    override func viewDidLoad() {

        super.viewDidLoad()

        button.center = self.view.center

        button.setTitle("anniu", for: .normal)

        button.backgroundColor = UIColor.blue

        self.view.addSubview(button)

        // Do any additional setup after loading the view, typically from a nib.

        button.setTarget(target: self, action: ViewController.onButtonTap, controlEvent: .TouchUpInside)

        

        button.addTarget(self, action: #selector(ViewController.action), for: .touchUpInside)

    }

    @objc func action(){

        button.performActionForControlEvent(controlEvent: .TouchUpInside)

    }

    func onButtonTap() {

        print("Button click")

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }





}

如果要這樣使用,封裝的意義在哪里,不是畫蛇添足嗎?求大神解答,謝謝。

您還未登錄,請(qǐng)先登錄

熱門帖子

最新帖子

?