Files
note/Note/MoreMenuBarButton.swift
T

88 lines
2.7 KiB
Swift

//
// MoreMenuBarButton.swift
// Note
//
// Created by fish on 2026/7/12.
//
import SwiftUI
struct MoreMenuBarButton: UIViewRepresentable {
@Binding var text: String
@Binding var showCopied: Bool
func makeUIView(context: Context) -> UIView {
let button = makeGlassButton()
button.menu = context.coordinator.makeMenu()
button.showsMenuAsPrimaryAction = true
let barButtonItem = UIBarButtonItem(customView: button)
context.coordinator.barButtonItem = barButtonItem
context.coordinator.button = button
return button
}
func updateUIView(_ uiView: UIView, context: Context) {
context.coordinator.button?.menu = context.coordinator.makeMenu()
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
private func makeGlassButton() -> UIButton {
let button = UIButton(type: .system)
button.setImage(UIImage(systemName: "ellipsis"), for: .normal)
button.tintColor = UIColor.label
button.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
button.layer.cornerRadius = 22
button.clipsToBounds = true
let blurEffect = UIBlurEffect(style: .systemUltraThinMaterial)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = button.bounds
blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
blurView.isUserInteractionEnabled = false
button.insertSubview(blurView, at: 0)
return button
}
class Coordinator {
var parent: MoreMenuBarButton
weak var barButtonItem: UIBarButtonItem?
weak var button: UIButton?
init(_ parent: MoreMenuBarButton) {
self.parent = parent
}
func makeMenu() -> UIMenu {
let copyAction = UIAction(
title: "复制",
image: UIImage(systemName: "doc.on.doc"),
attributes: parent.text.isEmpty ? .disabled : [],
handler: { [weak self] _ in
UIPasteboard.general.string = self?.parent.text ?? ""
self?.parent.showCopied = true
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
self?.parent.showCopied = false
}
}
)
let clearAction = UIAction(
title: "清除",
image: UIImage(systemName: "xmark.circle"),
attributes: parent.text.isEmpty ? [.disabled, .destructive] : .destructive,
handler: { [weak self] _ in
self?.parent.text = ""
}
)
return UIMenu(title: "", children: [copyAction, clearAction])
}
}
}