Implementing multi cast of delegate in Swift.
Copy SwiftMulticastDelegate.swift
to your project
pod 'SwiftMulticastDelegate', :git => 'https://github.com/chenmingbiao/SwiftMulticastDelegate.git'
You can use Swift Package Manager and specify a dependency in Package.swift
by adding this:
.Package(url: "https://github.com/chenmingbiao/SwiftMulticastDelegate.git", majorVersion: 1)
Import the module
import SwiftMulticastDelegate
- Add to your class:
let delegate = SwiftMulticastDelegate<MyProtocol>()
- Other classes must add as a delegate:
obj.delegate.add(self)
- When you need to notify your delegates:
multicastDelegate.invoke { delegate in delegate.func() }
Alternative version:
- Add to your class:
let delegate = SwiftMulticastDelegate<MyProtocol>()
- Other classes must add as a delegate:
obj.delegate += self
- When you need to notify your delegates:
multicastDelegate => { $0.func() }
// MARK: - MyButtonDelegate
protocol MyButtonDelegate: class {
func didTap()
}
// MARK: - MyButton
class MyButton: UIButton {
var delegate = SwiftMulticastDelegate<MyButtonDelegate>()
override init(frame: CGRect) {
super.init(frame: frame)
self.setTitle("Action", for: .normal)
self.setTitleColor(UIColor.blue, for: .normal)
self.addTarget(self, action: #selector(didTap), for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func didTap() {
delegate => {
$0.didTap()
}
}
}
// MARK: - SubView
class SubView: UIView {
var name = ""
}
extension SubView: MyButtonDelegate {
func didTap() {
print("\(name) did tap")
}
}
// MARK: - ViewController
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = MyButton(frame: CGRect(x: 0, y: 0, width: 100, height: 40))
button.center = self.view.center
self.view.addSubview(button)
let subview1 = SubView()
subview1.name = "subview@1"
button.delegate += subview1
self.view.addSubview(subview1)
let subview2 = SubView()
subview2.name = "subview@2"
button.delegate += subview2
self.view.addSubview(subview2)
/* Add Array */
// button.delegate += [subview1, subview2]
/* Rmove Array */
// button.delegate -= [subview1, subview2]
}
}
Simplify multicast usage
+=
calls add(_ delegate: T)
or add(_ delegate: [T])
-=
calls remove(_ delegate: T)
or remove(_ delegate: [T])
=>
calls invoke(_ invocation: (T) -> ())
SwiftMulticastDelegate
is available under the MIT license.