Skip to content

Instantly share code, notes, and snippets.

@vialyx
Created February 14, 2021 20:43
Show Gist options
  • Save vialyx/e458b10233f4d3549f67bfffdef389a1 to your computer and use it in GitHub Desktop.
Save vialyx/e458b10233f4d3549f67bfffdef389a1 to your computer and use it in GitHub Desktop.
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
typealias EmptyClosure = () -> Void
class ActionableTextField: UITextField {
private var cancelAction: EmptyClosure?
private var doneAction: EmptyClosure?
func addToolbarWithActions(cancel: EmptyClosure? = nil, done: EmptyClosure? = nil) {
cancelAction = cancel
doneAction = done
let toolbar = UIToolbar(frame: CGRect(x: 0,
y: 0,
width: UIScreen.main.bounds.width,
height: 50))
toolbar.barStyle = UIBarStyle.default
toolbar.items = [
UIBarButtonItem(title: "Cancel",
style: .plain,
target: self,
action: #selector(cancel(sender:))),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "Done",
style: .plain,
target: self,
action: #selector(done(sender:)))
]
toolbar.sizeToFit()
inputAccessoryView = toolbar
}
@objc
private func cancel(sender: AnyObject) {
cancelAction?()
}
@objc
private func done(sender: AnyObject) {
doneAction?()
}
}
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let label = ActionableTextField()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.text = "Hello World!"
label.textColor = .black
label.addToolbarWithActions { [unowned label] in
// TBD
label.text = "cancelled"
} done: {
label.text = "done"
}
view.addSubview(label)
self.view = view
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment