AvatarButton.swift 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //
  2. // SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  3. // SPDX-License-Identifier: GPL-3.0-or-later
  4. //
  5. import UIKit
  6. import SDWebImage
  7. @objcMembers class AvatarButton: UIButton {
  8. private var currentRequest: SDWebImageCombinedOperation?
  9. public func cancelCurrentRequest() {
  10. self.currentRequest?.cancel()
  11. }
  12. // MARK: - Init
  13. override init(frame: CGRect) {
  14. super.init(frame: frame)
  15. self.commonInit()
  16. }
  17. required init?(coder: NSCoder) {
  18. super.init(coder: coder)
  19. self.commonInit()
  20. }
  21. private func commonInit() {
  22. self.layer.masksToBounds = true
  23. self.imageView?.contentMode = .scaleToFill
  24. self.imageView?.frame = self.frame
  25. self.contentVerticalAlignment = .fill
  26. self.contentHorizontalAlignment = .fill
  27. self.backgroundColor = .systemGray3
  28. }
  29. override func layoutSubviews() {
  30. super.layoutSubviews()
  31. self.layer.cornerRadius = self.frame.width / 2.0
  32. }
  33. // MARK: - Conversation avatars
  34. public func setAvatar(for room: NCRoom) {
  35. self.cancelCurrentRequest()
  36. self.currentRequest = AvatarManager.shared.getAvatar(for: room, with: self.traitCollection.userInterfaceStyle) { image in
  37. guard let image = image else {
  38. return
  39. }
  40. self.setImage(image, for: .normal)
  41. self.backgroundColor = .clear
  42. }
  43. }
  44. public func setGroupAvatar() {
  45. if let image = AvatarManager.shared.getGroupAvatar(with: self.traitCollection.userInterfaceStyle) {
  46. self.setImage(image, for: .normal)
  47. }
  48. }
  49. // MARK: - User avatars
  50. public func setActorAvatar(forMessage message: NCChatMessage) {
  51. self.setActorAvatar(forId: message.actorId, withType: message.actorType, withDisplayName: message.actorDisplayName, withRoomToken: message.token)
  52. }
  53. public func setActorAvatar(forId actorId: String?, withType actorType: String?, withDisplayName actorDisplayName: String?, withRoomToken roomToken: String?) {
  54. self.setActorAvatar(forId: actorId, withType: actorType, withDisplayName: actorDisplayName, withRoomToken: roomToken, using: nil)
  55. }
  56. public func setActorAvatar(forId actorId: String?, withType actorType: String?, withDisplayName actorDisplayName: String?, withRoomToken roomToken: String?, using account: TalkAccount?) {
  57. self.cancelCurrentRequest()
  58. self.currentRequest = AvatarManager.shared.getActorAvatar(forId: actorId, withType: actorType, withDisplayName: actorDisplayName, withRoomToken: roomToken, withStyle: self.traitCollection.userInterfaceStyle, usingAccount: account) { image in
  59. guard let image = image else {
  60. return
  61. }
  62. self.setImage(image, for: .normal)
  63. }
  64. }
  65. }