How to edit shortcut with ios swift touch

I want to know how to edit the text label while the application is running.

Example: The label "Tap to Change text" appears. when clicked by the user, it will be available for editing, and the user can enter text and enter. then it will change to a new text.

I know that this can be done using UITextFieldDelegate. but I don’t know how to approach him. because there is no way to set an action on a shortcut when the user touches it

+4
source share
3 answers

You cannot edit the label as you edit textField, but when the user clicks on the label, you can hide the label and display textField, and when the user finishes typing, you can hide the text screen again and show the label, and you can set the text to TextField 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 this helps.

+10
source

To add my 2c here and remind me of the style in recent versions of Stanford University Paul Hegarty, the setting can be done in the “didSet” label field - you can also set up different respondents for different labels in 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 will be as follows:

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

TapGesture (UITapGestureRecognizer) . , , , .

0

Source: https://habr.com/ru/post/1598153/


All Articles