RoomDescriptionTableViewCell.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //
  2. // SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
  3. // SPDX-License-Identifier: GPL-3.0-or-later
  4. //
  5. import Foundation
  6. @objc public protocol RoomDescriptionTableViewCellDelegate: AnyObject {
  7. @objc optional func roomDescriptionCellTextViewDidChange(_ cell: RoomDescriptionTableViewCell)
  8. @objc optional func roomDescriptionCellDidExceedLimit(_ cell: RoomDescriptionTableViewCell)
  9. @objc optional func roomDescriptionCellDidEndEditing(_ cell: RoomDescriptionTableViewCell)
  10. }
  11. @objcMembers public class RoomDescriptionTableViewCell: UITableViewCell, UITextViewDelegate {
  12. public weak var delegate: RoomDescriptionTableViewCellDelegate?
  13. @IBOutlet weak var textView: UITextView!
  14. public static var identifier = "RoomDescriptionCellIdentifier"
  15. public static var nibName = "RoomDescriptionTableViewCell"
  16. public var characterLimit: Int = -1
  17. public override func awakeFromNib() {
  18. super.awakeFromNib()
  19. self.textView.dataDetectorTypes = .all
  20. self.textView.textContainer.lineFragmentPadding = 0
  21. self.textView.textContainerInset = .zero
  22. self.textView.isScrollEnabled = false
  23. self.textView.isEditable = false
  24. self.textView.delegate = self
  25. }
  26. // MARK: - UITextView delegate
  27. public func textViewDidChange(_ textView: UITextView) {
  28. self.delegate?.roomDescriptionCellTextViewDidChange?(self)
  29. }
  30. public func textViewDidEndEditing(_ textView: UITextView) {
  31. self.delegate?.roomDescriptionCellDidEndEditing?(self)
  32. }
  33. public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  34. // Prevent crashing undo bug
  35. // https://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield
  36. let currentCharacterCount = textView.text?.count ?? 0
  37. if range.length + range.location > currentCharacterCount {
  38. return false
  39. }
  40. // Check character limit
  41. let newLength = currentCharacterCount + text.count - range.length
  42. let limitExceeded = self.characterLimit > 0 && newLength > self.characterLimit
  43. if limitExceeded {
  44. self.delegate?.roomDescriptionCellDidExceedLimit?(self)
  45. }
  46. return !limitExceeded
  47. }
  48. }