Created
December 29, 2015 19:10
-
-
Save justinmakaila/7537975fd75fa485abd9 to your computer and use it in GitHub Desktop.
UIKit extensions for adding Reactive Cocoa Support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import ReactiveCocoa | |
// MARK: - UIControl | |
extension UIControl { | |
func producerForEvent<T where T: UIControl>(controlEvent: UIControlEvents) -> SignalProducer<T, NoError> { | |
return self.rac_signalForControlEvents(controlEvent) | |
.toSignalProducer() | |
.map { (object: AnyObject?) -> T? in | |
if let control = object as? T { | |
return control | |
} | |
return nil | |
} | |
.ignoreNil() | |
.flatMap(.Latest) { control in | |
return SignalProducer(value: control) | |
} | |
.flatMapError { error in return SignalProducer<T, NoError>.empty } | |
} | |
} | |
// MARK: - UIDatePicker | |
extension UIDatePicker { | |
func dateSignal() -> SignalProducer<NSDate, NoError> { | |
return self.producerForEvent(.ValueChanged) | |
.flatMap(.Latest) { (datePicker: UIDatePicker) in | |
return SignalProducer(value: datePicker.date) | |
} | |
} | |
} | |
// MARK: - UIRefreshControl | |
extension UIRefreshControl { | |
func refreshingProducer() -> SignalProducer<Bool, NoError> { | |
return self.producerForEvent(.ValueChanged) | |
.flatMap(.Latest) { (refreshControl: UIRefreshControl) in | |
return SignalProducer(value: refreshControl.refreshing) | |
} | |
} | |
} | |
// MARK: - UITextField | |
extension UITextField { | |
func textProducer() -> SignalProducer<String, NoError> { | |
return self.rac_textSignal().toSignalProducer() | |
.map { object in | |
if let string = object as? String { | |
return string | |
} | |
return "" | |
} | |
.flatMapError { _ in SignalProducer<String, NoError>.empty } | |
} | |
} | |
extension UITextView { | |
func textProducer() -> SignalProducer<String, NoError> { | |
return self.rac_textSignal().toSignalProducer() | |
.map { object in | |
if let string = object as? String { | |
return string | |
} | |
return "" | |
} | |
.flatMapError { _ in SignalProducer<String, NoError>.empty } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment