// // AttachmentsContainerView.swift // Tusker // // Created by Shadowfacts on 6/16/19. // Copyright © 2019 Shadowfacts. All rights reserved. // import UIKit import Pachyderm class AttachmentsContainerView: UIView { var delegate: AttachmentViewDelegate? override func awakeFromNib() { super.awakeFromNib() self.isUserInteractionEnabled = true } func updateUI(status: Status) { let attachments = status.attachments.filter { $0.kind == .image } if attachments.count > 0 { self.isHidden = false let mainView: UIView switch attachments.count { case 1: mainView = createAttachmentView(attachments[0]) case 2: mainView = createAttachmentsStack(axis: .horizontal, arrangedSubviews: [ createAttachmentView(attachments[0]), createAttachmentView(attachments[1]) ]) case 3: mainView = createAttachmentsStack(axis: .horizontal, arrangedSubviews: [ createAttachmentView(attachments[0]), createAttachmentsStack(axis: .vertical, arrangedSubviews: [ createAttachmentView(attachments[1]), createAttachmentView(attachments[2]) ]) ]) case 4: mainView = createAttachmentsStack(axis: .horizontal, arrangedSubviews: [ createAttachmentsStack(axis: .vertical, arrangedSubviews: [ createAttachmentView(attachments[0]), createAttachmentView(attachments[2]) ]), createAttachmentsStack(axis: .vertical, arrangedSubviews: [ createAttachmentView(attachments[1]), createAttachmentView(attachments[3]) ]) ]) default: fatalError("Too many attachments") } addSubview(mainView) NSLayoutConstraint.activate([ mainView.leadingAnchor.constraint(equalTo: leadingAnchor), mainView.trailingAnchor.constraint(equalTo: trailingAnchor), mainView.topAnchor.constraint(equalTo: topAnchor), mainView.bottomAnchor.constraint(equalTo: bottomAnchor) ]) } else { self.isHidden = true subviews.forEach { $0.removeFromSuperview() } } } private func createAttachmentView(_ attachment: Attachment) -> AttachmentView { let attachmentView = AttachmentView(attachment: attachment) attachmentView.delegate = delegate attachmentView.translatesAutoresizingMaskIntoConstraints = false return attachmentView } private func createAttachmentsStack(axis: NSLayoutConstraint.Axis, arrangedSubviews: [UIView]) -> UIStackView { let stack = UIStackView(arrangedSubviews: arrangedSubviews) stack.axis = axis stack.spacing = 8 stack.translatesAutoresizingMaskIntoConstraints = false return stack } }