Tusker/Tusker/Views/Attachment Cells/ComposeAttachmentTableViewC...

95 lines
3.1 KiB
Swift

//
// ComposeAttachmentTableViewCell.swift
// Tusker
//
// Created by Shadowfacts on 3/13/20.
// Copyright © 2020 Shadowfacts. All rights reserved.
//
import UIKit
import Photos
import AVFoundation
protocol ComposeAttachmentTableViewCellDelegate: class {
func removeAttachment(_ cell: ComposeAttachmentTableViewCell)
func attachmentDescriptionChanged(_ cell: ComposeAttachmentTableViewCell)
}
class ComposeAttachmentTableViewCell: UITableViewCell {
weak var delegate: ComposeAttachmentTableViewCellDelegate?
@IBOutlet weak var assetImageView: UIImageView!
@IBOutlet weak var descriptionTextView: UITextView!
@IBOutlet weak var descriptionPlaceholderLabel: UILabel!
@IBOutlet weak var removeButton: UIButton!
var attachment: CompositionAttachment!
override func awakeFromNib() {
super.awakeFromNib()
assetImageView.layer.masksToBounds = true
assetImageView.layer.cornerRadius = 8
descriptionTextView.delegate = self
}
func updateUI(for attachment: CompositionAttachment) {
self.attachment = attachment
descriptionTextView.text = attachment.attachmentDescription
updateDescriptionPlaceholderLabel()
assetImageView.contentMode = .scaleAspectFill
assetImageView.backgroundColor = .secondarySystemBackground
switch attachment.data {
case let .image(image):
assetImageView.image = image
case let .asset(asset):
let size = CGSize(width: 80, height: 80)
PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: nil) { (image, _) in
guard self.attachment == attachment else { return }
self.assetImageView.image = image
}
case let .video(url):
let asset = AVURLAsset(url: url)
let imageGenerator = AVAssetImageGenerator(asset: asset)
if let cgImage = try? imageGenerator.copyCGImage(at: .zero, actualTime: nil) {
assetImageView.image = UIImage(cgImage: cgImage)
}
case let .drawing(drawing):
assetImageView.image = drawing.imageInLightMode(from: drawing.bounds)
assetImageView.contentMode = .scaleAspectFit
assetImageView.backgroundColor = .white
}
}
func updateDescriptionPlaceholderLabel() {
descriptionPlaceholderLabel.isHidden = !descriptionTextView.text.isEmpty
}
func setEnabled(_ enabled: Bool) {
descriptionTextView.isEditable = enabled
removeButton.isEnabled = enabled
}
override func prepareForReuse() {
super.prepareForReuse()
assetImageView.image = nil
}
@IBAction func removeButtonPressed(_ sender: Any) {
delegate?.removeAttachment(self)
}
}
extension ComposeAttachmentTableViewCell: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
attachment.attachmentDescription = textView.text
updateDescriptionPlaceholderLabel()
delegate?.attachmentDescriptionChanged(self)
}
}