Skip to content

Instantly share code, notes, and snippets.

@wata
Created April 17, 2021 15:55
Show Gist options
  • Save wata/481d363c501c6ad3d21216de6932c533 to your computer and use it in GitHub Desktop.
Save wata/481d363c501c6ad3d21216de6932c533 to your computer and use it in GitHub Desktop.
struct CopyableText: UIViewRepresentable {
let text: String
init(_ text: String) {
self.text = text
}
func makeUIView(context: Context) -> UILabel {
let label = CopyableLabel()
label.text = text
label.setContentHuggingPriority(.required, for: .horizontal)
label.setContentHuggingPriority(.required, for: .vertical)
return label
}
func updateUIView(_ uiView: UILabel, context: Context) {}
}
private class CopyableLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
isUserInteractionEnabled = true
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap))
addGestureRecognizer(gestureRecognizer)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var canBecomeFirstResponder: Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return action == #selector(UIResponderStandardEditActions.copy)
}
override func copy(_ sender: Any?) {
UIPasteboard.general.string = text
UIMenuController.shared.hideMenu()
}
@objc private func handleTap() {
becomeFirstResponder()
if !UIMenuController.shared.isMenuVisible {
UIMenuController.shared.showMenu(from: self, rect: bounds)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment