I want native iOS copy and paste UI on UILabel

ぃ、小莉子 提交于 2019-12-23 16:22:47

问题


I want to create the native Copy and Paste experience that iOS provides when you tap and hold a UITextField - but I want it to work on a UILabel instead of a UITextField.

Is this possible, or is it something that only works with UITextField? Would I need to create my own custom UI and mess around in UIPasteboard or is there a more eloquent solution?

Here is a typical example, although it normally also shows the zoomed in circle:


回答1:


It is difficult to do the standard copy menu on the label. Or maybe at that time I tried but didnt succeed. So I just implemented a complete copy solution. I did it something like below -

import UIKit

class KGCopyableLabel: UILabel {

    override public var canBecomeFirstResponder: Bool {
        get {
            return true
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    func setup() {
        isUserInteractionEnabled = true
        addGestureRecognizer(UILongPressGestureRecognizer(
            target: self,
            action: #selector(showCopyMenu(sender:))
        ))
    }

    override func copy(_ sender: Any?) {
        UIPasteboard.general.string = text
        UIMenuController.shared.setMenuVisible(false, animated: true)
    }

    func showCopyMenu(sender: Any?) {
        becomeFirstResponder()
        let menu = UIMenuController.shared
        if !menu.isMenuVisible {
            menu.setTargetRect(bounds, in: self)
            menu.setMenuVisible(true, animated: true)
        }
    }

    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return (action == #selector(copy(_:)))
    }
}

You can then simple drag drop the Label in Storyboard and make it of the type KGCopyableLabel and it should work



来源:https://stackoverflow.com/questions/45541208/i-want-native-ios-copy-and-paste-ui-on-uilabel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!