spaceMonkey
spaceMonkey

Reputation: 4615

iOS create "copy paste" like popover (UIMenuController) in UITableView

Im trying to create a intractable pop over similar to how apples "copy", "paste". Im not sure how to do it.

enter image description here

Is there a 3rd party lib or is it a native component ?

Upvotes: 4

Views: 1715

Answers (1)

spaceMonkey
spaceMonkey

Reputation: 4615

If it helps anyone, the keyword to look for is "UIMenuController"

I finally managed to solve this by implementing a custom UITableViewCell

override func setSelected(_ selected: Bool, animated: Bool) {

        super.setSelected(selected, animated: animated)
        let showPasswordItem = UIMenuItem(title: "Show Password", action: #selector(showPass(_:)))
        let copyUserNameItem = UIMenuItem(title: "Copy Username", action: #selector(copyUsername(_:)))
        let copyPasswordItem = UIMenuItem(title: "Copy Password", action: #selector(copyPass(_:)))
        self.isPasswordShowing = !self.password.isSecureTextEntry
        UIMenuController.shared.menuItems?.removeAll()
        UIMenuController.shared.menuItems = [copyPasswordItem,copyUserNameItem,showPasswordItem,hidePasswordItem]
        UIMenuController.shared.update()

        if selected {
            self.becomeFirstResponder()
            let menu = UIMenuController.shared
            menu.setTargetRect(self.contentView.frame, in: self.contentView.superview!)
            menu.setMenuVisible(true, animated: true)
        }
    }

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {

     return  action == #selector(showPass(_:)) || action == #selector(copyUsername(_:)) || action == #selector(copyPass(_:))

}

override var canBecomeFirstResponder : Bool {
    return true
}

func showPass(_ send:AnyObject){
    self.password.isSecureTextEntry = false
    self.isPasswordShowing = true
}
func copyUsername(_ send:AnyObject){
    UIPasteboard.general.string = self.username.text
}
func copyPass(_ send:AnyObject){
    UIPasteboard.general.string = self.password.text
}
func hidePass(_ send:AnyObject){
    self.password.isSecureTextEntry = true
    self.isPasswordShowing = false
}

Upvotes: 2

Related Questions