Tusker/Tusker/Views/VisualEffectImageButton.swift

73 lines
2.8 KiB
Swift

//
// VisualEffectImageButton.swift
// Tusker
//
// Created by Shadowfacts on 6/26/20.
// Copyright © 2020 Shadowfacts. All rights reserved.
//
import UIKit
class VisualEffectImageButton: UIControl {
@IBInspectable
var image: UIImage! {
didSet {
imageView?.image = image
}
}
var menu: UIMenu?
private(set) var imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
let blur = UIBlurEffect(style: .prominent)
let blurView = UIVisualEffectView(effect: blur)
blurView.translatesAutoresizingMaskIntoConstraints = false
let vibrancy = UIVibrancyEffect(blurEffect: blur, style: .label)
let vibrancyView = UIVisualEffectView(effect: vibrancy)
vibrancyView.translatesAutoresizingMaskIntoConstraints = false
imageView = UIImageView(image: self.image)
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
vibrancyView.contentView.addSubview(imageView)
blurView.contentView.addSubview(vibrancyView)
addSubview(blurView)
NSLayoutConstraint.activate([
blurView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
blurView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
blurView.topAnchor.constraint(equalTo: self.topAnchor),
blurView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
vibrancyView.leadingAnchor.constraint(equalTo: blurView.leadingAnchor),
vibrancyView.trailingAnchor.constraint(equalTo: blurView.trailingAnchor),
vibrancyView.topAnchor.constraint(equalTo: blurView.topAnchor),
vibrancyView.bottomAnchor.constraint(equalTo: blurView.bottomAnchor),
imageView.leadingAnchor.constraint(equalTo: vibrancyView.leadingAnchor, constant: 2),
imageView.trailingAnchor.constraint(equalTo: vibrancyView.trailingAnchor, constant: -2),
imageView.topAnchor.constraint(equalTo: vibrancyView.topAnchor, constant: 2),
imageView.bottomAnchor.constraint(equalTo: vibrancyView.bottomAnchor, constant: -2),
])
addInteraction(UIContextMenuInteraction(delegate: self))
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onTap)))
isAccessibilityElement = true
}
@objc private func onTap() {
sendActions(for: .touchUpInside)
}
override func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
guard let menu = menu else { return nil }
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { (_) -> UIMenu? in
return menu
}
}
}