How can I edit a UILabel upon touching it in Swift?

You can not edit label like you edit textField but when user click on label you can hide label and unhide textField and when user finish entering text you can again hide textField and unhide label and you can assign textField's text to label this way:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var lbl: UILabel!
    @IBOutlet weak var textF: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        textF.delegate = self
        textF.hidden = true
        lbl.userInteractionEnabled = true
        let aSelector : Selector = "lblTapped"
        let tapGesture = UITapGestureRecognizer(target: self, action: aSelector)
        tapGesture.numberOfTapsRequired = 1
        lbl.addGestureRecognizer(tapGesture)
    }

    func lblTapped(){
        lbl.hidden = true
        textF.hidden = false
        textF.text = lbl.text
    }

    func textFieldShouldReturn(userText: UITextField) -> Bool {
        userText.resignFirstResponder()
        textF.hidden = true
        lbl.hidden = false
        lbl.text = textF.text
        return true
    }
}

Hope it will help.


To add my 2c here and remind me of the style in the latest Stanford University Paul Hegarty videos, the setup can be done in the "didSet" of the label Field - you can also set up different responders for different labels this way:

@IBOutlet weak var lblField: UILabel! {
    didSet {
        let recognizer = UILongPressGestureRecognizer()
        recognizer.addTarget(self, action: #selector(ViewController.lbllongpress))
        lblField.addGestureRecognizer(recognizer)
    }
}

and then the implementation becomes:

func lbllongpress(gesture: UILongPressGestureRecognizer) {
    switch gesture.state {
    case UIGestureRecognizerState.began:
        break;
    case UIGestureRecognizerState.ended:
        // Implementation here...
    default: break
    }
}