Skip to content

Instantly share code, notes, and snippets.

View natebirkholz's full-sized avatar
💻
Codin’

Nate Birkholz natebirkholz

💻
Codin’
View GitHub Profile
let tapClosure: (UITapGestureRecognizer) -> () = { (tapRecognizer) in
print("In tap closure")
}
let recognizer = ClosureGestureRecognizer(action: tapClosure)
class ClosureGestureRecognizer<GestureRecognizer: UIGestureRecognizer> {
fileprivate var recognizer: GestureRecognizer
private var actionHandler: ((GestureRecognizer) -> Void)
init(action: @escaping (GestureRecognizer) -> ()) {
self.recognizer = GestureRecognizer()
self.actionHandler = action
self.recognizer.addTarget(self, action: #selector(handleAction))
}
let closure: () -> () = {
print("In Closure!")
}
let button = ClosureButton(frame: CGRect(x: 10, y: 10, width: 100, height: 20))
button.setTitle("Closure", for: .normal)
button.sizeToFit()
button.addClosureForEvent(.touchUpInside, closure: closure)
class ClosureButton: UIButton {
private var actionHandler: (() -> ())?
func addClosureForEvent(_ event: UIControlEvents, closure: @escaping () ->()) {
self.addTarget(self, action: #selector(handleAction), for: event)
}
@objc private func handleAction() {
actionHandler?()
}
class HelloViewController: UIViewController {
let label = UILabel(frame: .zero)
override func viewDidLoad() {
super.viewDidLoad()
label.text = "Hello world!"
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFont(ofSize: 16.0, weight: .medium)
label.textColor = .black
label.textAlignment = .center
let attributes = [ NSForegroundColorAttributeName : self.view.tintColor ]
let attributedString = NSAttributedString(string: NSLocalizedString("Sign In", comment: ""), attributes: attributes)
warns: (Expression implicitly coerced from 'UIColor?' to Any)
right way:
let attributes: [ String : UIColor ]
if let maybeAttributes = [ NSForegroundColorAttributeName : self.view.tintColor ] {
attributes = maybeAttributes
} else {
assertionFailure("self.view.tintColor is nil")
class SuperClass {
var aBool : Bool = false {
didSet {
print(aBool)
}
}
}