Friday, 3 May 2019

UIMenuViewController example

import UIKit
import ContactsUI

class ViewController: UIViewController , CNContactViewControllerDelegate {

    @IBOutlet weak var TF: UITextField!
    @IBOutlet weak var lbl: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
//        TF.delegate = self
        
        //https://github.com/NSHipster/articles/blob/master/2013-07-22-uimenucontroller.md
        //http://themainthread.com/blog/2013/04/a-simple-custom-view-that-supports-uimenucontroller-on-ios.html
        //https://www.otz.li/2019/01/06/copy-a-uilabel-in-ios/
        
        self.lbl.isUserInteractionEnabled = true
        let longPress = UILongPressGestureRecognizer.init(target: self, action: #selector((longPressFunctin(_:))))
        self.lbl.addGestureRecognizer(longPress)
        
    }
    
    @objc func longPressFunctin(_ gestureRecognizer: UILongPressGestureRecognizer) {
        lbl.becomeFirstResponder()
        let menu = UIMenuController.shared
        if !menu.isMenuVisible {
            menu.setTargetRect(lbl.frame, in: view)
            menu.setMenuVisible(true, animated: true)
        }
    }
    
    override func copy(_ sender: Any?) {
        let board = UIPasteboard.general
        board.string = lbl.text
        let menu = UIMenuController.shared
        menu.setMenuVisible(false, animated: true)
    }
    
    override var canBecomeFirstResponder: Bool {
        return true
    }
    
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return action == #selector(copy(_:))
    }
    
    //Add number to contacts
    @IBAction func addNumberToContacts(_ sender: Any) {
        addPhoneNumber(phNo: "09955667788")
    }
    
    //Add phone number to addressbook
    func addPhoneNumber(phNo : String) {
        if #available(iOS 9.0, *) {
            let store = CNContactStore()
            let contact = CNMutableContact()
            let homePhone = CNLabeledValue(label: CNLabelWork, value: CNPhoneNumber(stringValue :phNo ))
            contact.phoneNumbers = [homePhone]
            let controller = CNContactViewController(forUnknownContact : contact)
            controller.contactStore = store
            controller.delegate = self
            self.navigationController?.setNavigationBarHidden(false, animated: true)
            self.navigationController!.pushViewController(controller, animated: true)
        }
    }
    
}
    

    

No comments:

Post a Comment

Difference between == and ===

Difference between == and === https://stackoverflow.com/questions/24002819/difference-between-and == operator checks if their ...