我有代碼複製標籤中的數字。從標籤複製菜單
我有一個用於複製的按鈕,我該如何使它在點擊它時打開照片中的菜單,然後點擊複製按鈕?
@IBAction func copybutton(_ sender: UIButton) {
UIPasteboard.general.string = displayResultLabel.text
}
我有代碼複製標籤中的數字。從標籤複製菜單
我有一個用於複製的按鈕,我該如何使它在點擊它時打開照片中的菜單,然後點擊複製按鈕?
@IBAction func copybutton(_ sender: UIButton) {
UIPasteboard.general.string = displayResultLabel.text
}
從你的問題的信息微薄的量,希望我理解正確的問題。
我創建了一個具有UIViewController
和UILabel
和UIButton
的示例。
無論何時按下按鈕,屏幕都將顯示帶有三個按鈕(Copy
,Paste
,View Memory
)的操作表菜單。
當按下操作表中的Copy
按鈕時,我們將複製標籤的文本。
這是代碼:
注:
UILabel
命名displayResultLabel
。
UIButton
的動作名爲showActionSheetButtonAction
。
class ViewController: UIViewController {
@IBOutlet weak var displayResultLabel: UILabel!
@IBAction func showActionSheetButtonAction(_ sender: UIButton) {
let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionSheetController.addAction(
UIAlertAction(title: "Copy", style: .default, handler: { [weak self] _ in
guard let strongSelf = self else { return }
UIPasteboard.general.string = strongSelf.displayResultLabel.text
})
)
actionSheetController.addAction(
UIAlertAction(title: "Paste", style: .default, handler: { _ in
// Where to handle when the Paste button is pressed
})
)
actionSheetController.addAction(
UIAlertAction(title: "View Memory", style: .default, handler: { _ in
// Where to handle when the View Memory button is pressed
})
)
actionSheetController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(actionSheetController, animated: true, completion: nil)
}
}
謝謝,它的工作原理。這是我需要的)) – KVL
哦,是的,不客氣。 –
你需要繼承的UILabel
,並改變一些默認的東西來實現這一點,首先你需要設置userInteractionEnable = true
,默認情況下false
在UILabel
,你也需要重寫屬性canBecomeFirstResponder
這是也默認爲假後,您可以顯示菜單成爲firstResponder標籤,並使用帶有longPressGestureRecognizer的UIMenuController
,此類完整代碼位於此處
使用此的UILabel子類
import UIKit
class ContextMenuLabel: UILabel {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override func awakeFromNib() {
super.awakeFromNib()
self.isUserInteractionEnabled = true
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.showContextMenu))
self.addGestureRecognizer(longPressGesture)
}
func showContextMenu()
{
self.becomeFirstResponder()
UIMenuController.shared.setTargetRect(self.frame, in: self.superview!)
let itemCopy = UIMenuItem(title: "Copy", action: #selector(self.copyAction))
UIMenuController.shared.arrowDirection = .down
UIMenuController.shared.menuItems = [itemCopy]
UIMenuController.shared.setMenuVisible(true, animated: true)
debugPrint(UIMenuController.shared.menuFrame)
}
func copyAction()
{
UIPasteboard.general.string = self.text
}
override var canBecomeFirstResponder: Bool{
get{
return true
}
}
}
結果
希望這有助於
您只想動作片來進行復製圖標? –
@MohammadBashirSidani我需要按下此按鈕才能打開帶有複製功能的菜單。 – KVL