metatext-app-ios-iphone-ipad/Views/UIKit/SecondaryNavigationButton.s...

75 lines
2.6 KiB
Swift
Raw Normal View History

2021-01-21 09:45:09 +01:00
// Copyright © 2021 Metabolist. All rights reserved.
import Combine
2021-02-23 00:59:33 +01:00
import SDWebImage
2021-01-21 09:45:09 +01:00
import UIKit
import ViewModels
final class SecondaryNavigationButton: UIBarButtonItem {
private var cancellables = Set<AnyCancellable>()
init(viewModel: NavigationViewModel, rootViewModel: RootViewModel) {
super.init()
let button = UIButton(
type: .custom,
primaryAction: UIAction { _ in viewModel.presentingSecondaryNavigation = true })
2021-02-01 20:53:47 +01:00
button.accessibilityLabel = NSLocalizedString("secondary-navigation-button.accessibility-title", comment: "")
2021-01-21 09:45:09 +01:00
button.imageView?.contentMode = .scaleAspectFill
button.layer.cornerRadius = .barButtonItemDimension / 2
button.clipsToBounds = true
customView = button
NSLayoutConstraint.activate([
button.widthAnchor.constraint(equalToConstant: .barButtonItemDimension),
button.heightAnchor.constraint(equalToConstant: .barButtonItemDimension)
])
2021-01-26 01:06:35 +01:00
viewModel.identityContext.$identity.sink {
2021-02-23 00:59:33 +01:00
button.sd_setImage(
2021-01-21 09:45:09 +01:00
with: $0.image,
for: .normal,
2021-02-23 00:59:33 +01:00
placeholderImage: UIImage(systemName: "line.horizontal.3"))
2021-01-21 09:45:09 +01:00
}
.store(in: &cancellables)
2021-02-23 00:59:33 +01:00
let imageTransformer = SDImageRoundCornerTransformer(
radius: .greatestFiniteMagnitude,
corners: .allCorners,
borderWidth: 0,
borderColor: nil)
2021-01-31 07:30:12 +01:00
2021-01-21 09:45:09 +01:00
viewModel.$recentIdentities.sink { identities in
button.menu = UIMenu(children: identities.map { identity in
UIDeferredMenuElement { completion in
let action = UIAction(title: identity.handle) { _ in
rootViewModel.identitySelected(id: identity.id)
}
if let image = identity.image {
2021-02-23 00:59:33 +01:00
SDWebImageManager.shared.loadImage(
with: image,
options: [.transformAnimatedImage],
context: [.imageTransformer: imageTransformer],
progress: nil) { (image, _, _, _, _, _) in
action.image = image
2021-01-21 09:45:09 +01:00
completion([action])
}
} else {
completion([action])
}
}
})
}
.store(in: &cancellables)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}