PollMessageView.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
  3. // SPDX-License-Identifier: GPL-3.0-or-later
  4. //
  5. import UIKit
  6. class PollMessageView: UIView {
  7. @IBOutlet var contentView: UIView!
  8. @IBOutlet weak var pollImageLabel: UILabel!
  9. @IBOutlet weak var pollTitleTextView: UITextView!
  10. override init(frame: CGRect) {
  11. super.init(frame: frame)
  12. commonInit()
  13. }
  14. required init?(coder aDecoder: NSCoder) {
  15. super.init(coder: aDecoder)
  16. commonInit()
  17. }
  18. func commonInit() {
  19. Bundle.main.loadNibNamed("PollMessageView", owner: self, options: nil)
  20. contentView.frame = self.bounds
  21. contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  22. self.addSubview(contentView)
  23. // Poll image
  24. pollImageLabel.attributedText = pollImageAttributedString()
  25. // Poll title
  26. configureTitleTextView(with: pollTitleTextView)
  27. }
  28. func pollImageAttributedString() -> NSAttributedString {
  29. guard let pollImage = UIImage(systemName: "chart.bar") else {
  30. return NSAttributedString()
  31. }
  32. return NSAttributedString(attachment: NSTextAttachment(image: pollImage))
  33. .withFont(.preferredFont(for: .body, weight: .medium))
  34. .withTextColor(.label)
  35. }
  36. func configureTitleTextView(with textView: UITextView) {
  37. textView.textContainerInset = .zero
  38. textView.textContainer.lineFragmentPadding = 0
  39. textView.font = .preferredFont(for: .body, weight: .medium)
  40. }
  41. func pollMessageBodyHeight(with title: String, width: CGFloat) -> CGFloat {
  42. let pollImageWidth = pollImageAttributedString().boundingRect(
  43. with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude),
  44. options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).width
  45. let titleTextViewMaxWidth = ceil(width - (pollImageWidth + 30)) // 3 * padding (10)
  46. let titleTextView = UITextView(frame: .zero)
  47. configureTitleTextView(with: titleTextView)
  48. titleTextView.text = title
  49. let titleTextViewHeight = ceil(titleTextView.sizeThatFits(CGSize(width: titleTextViewMaxWidth, height: CGFloat.greatestFiniteMagnitude)).height)
  50. return titleTextViewHeight + 20 // 2 * padding (10)
  51. }
  52. }