TextFieldTableViewCell.swift 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //
  2. // TextFieldTableViewCell.swift
  3. // Naterade
  4. //
  5. // Created by Nathan Racklyeft on 5/22/16.
  6. // Copyright © 2016 Nathan Racklyeft. All rights reserved.
  7. //
  8. import UIKit
  9. public protocol TextFieldTableViewCellDelegate: class {
  10. func textFieldTableViewCellDidBeginEditing(_ cell: TextFieldTableViewCell)
  11. func textFieldTableViewCellDidEndEditing(_ cell: TextFieldTableViewCell)
  12. func textFieldTableViewCellDidChangeEditing(_ cell: TextFieldTableViewCell)
  13. }
  14. // MARK: - Default Implementations
  15. extension TextFieldTableViewCellDelegate {
  16. public func textFieldTableViewCellDidChangeEditing(_ cell: TextFieldTableViewCell) { }
  17. }
  18. public class TextFieldTableViewCell: UITableViewCell, UITextFieldDelegate {
  19. @IBOutlet public weak var unitLabel: UILabel? {
  20. didSet {
  21. // Setting this color in code because the nib isn't being applied correctly
  22. if #available(iOSApplicationExtension 13.0, *) {
  23. unitLabel?.textColor = .secondaryLabel
  24. }
  25. }
  26. }
  27. @IBOutlet public weak var textField: UITextField! {
  28. didSet {
  29. textField.delegate = self
  30. textField.addTarget(self, action: #selector(textFieldEditingChanged), for: .editingChanged)
  31. // Setting this color in code because the nib isn't being applied correctly
  32. if #available(iOSApplicationExtension 13.0, *) {
  33. textField.textColor = .label
  34. }
  35. }
  36. }
  37. public var maximumTextLength: Int?
  38. override public func prepareForReuse() {
  39. super.prepareForReuse()
  40. textField.delegate = nil
  41. unitLabel?.text = nil
  42. }
  43. public weak var delegate: TextFieldTableViewCellDelegate?
  44. @objc private func textFieldEditingChanged() {
  45. delegate?.textFieldTableViewCellDidChangeEditing(self)
  46. }
  47. // MARK: - UITextFieldDelegate
  48. public func textFieldDidBeginEditing(_ textField: UITextField) {
  49. delegate?.textFieldTableViewCellDidBeginEditing(self)
  50. }
  51. public func textFieldDidEndEditing(_ textField: UITextField) {
  52. delegate?.textFieldTableViewCellDidEndEditing(self)
  53. }
  54. public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  55. guard let maximumTextLength = maximumTextLength else {
  56. return true
  57. }
  58. let text = textField.text ?? ""
  59. let allText = (text as NSString).replacingCharacters(in: range, with: string)
  60. if allText.count <= maximumTextLength {
  61. return true
  62. } else {
  63. textField.text = String(allText.prefix(maximumTextLength))
  64. return false
  65. }
  66. }
  67. }