UITextField+Rx.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // UITextField+Rx.swift
  3. // RxCocoa
  4. //
  5. // Created by Krunoslav Zaher on 2/21/15.
  6. // Copyright © 2015 Krunoslav Zaher. All rights reserved.
  7. //
  8. #if os(iOS) || os(tvOS)
  9. import RxSwift
  10. import UIKit
  11. extension Reactive where Base: UITextField {
  12. /// Reactive wrapper for `text` property.
  13. public var text: ControlProperty<String?> {
  14. return value
  15. }
  16. /// Reactive wrapper for `text` property.
  17. public var value: ControlProperty<String?> {
  18. return base.rx.controlPropertyWithDefaultEvents(
  19. getter: { textField in
  20. textField.text
  21. },
  22. setter: { textField, value in
  23. // This check is important because setting text value always clears control state
  24. // including marked text selection which is imporant for proper input
  25. // when IME input method is used.
  26. if textField.text != value {
  27. textField.text = value
  28. }
  29. }
  30. )
  31. }
  32. /// Bindable sink for `attributedText` property.
  33. public var attributedText: ControlProperty<NSAttributedString?> {
  34. return base.rx.controlPropertyWithDefaultEvents(
  35. getter: { textField in
  36. textField.attributedText
  37. },
  38. setter: { textField, value in
  39. // This check is important because setting text value always clears control state
  40. // including marked text selection which is imporant for proper input
  41. // when IME input method is used.
  42. if textField.attributedText != value {
  43. textField.attributedText = value
  44. }
  45. }
  46. )
  47. }
  48. /// Bindable sink for `isSecureTextEntry` property.
  49. public var isSecureTextEntry: Binder<Bool> {
  50. return Binder(self.base) { textField, isSecureTextEntry in
  51. textField.isSecureTextEntry = isSecureTextEntry
  52. }
  53. }
  54. }
  55. #endif