1
Good afternoon, I have a button in my application that the value will be changed as the button is selected, must open a field for the user to type and consequently it takes the entered value and changes the label.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var fieldInput: UITextField! // Campo
@IBOutlet weak var charOne: UIButton!
@IBOutlet weak var charTwo: UIButton!
@IBOutlet weak var charThree: UIButton!
@IBOutlet weak var charFour: UIButton!
var selectedButton: UIButton!
var savedText: String!
override func viewDidLoad() {
super.viewDidLoad()
// Atribuir delegate ao campo
fieldInput.isHidden = true
fieldInput.delegate = self
}
func textFieldShouldReturn(textFieldInput: UITextField) -> Bool
{
if (textFieldInput == self.fieldInput) {
// Guardar o texto do campo
savedText = textFieldInput.text
}
// Finalizar a edição
textFieldInput.resignFirstResponder()
return false;
}
@IBAction func didEditingEnd(sender: AnyObject) {
// Acção associada ao campo
selectedButton.setTitle(savedText, for: .normal)
fieldInput.isHidden = true
}
//UILongPressGestureRecognizer associado a cada botão
@IBAction func didLongPressButton(sender: AnyObject) {
if sender is UILongPressGestureRecognizer &&
sender.state == UIGestureRecognizerState.began {
if let button = sender.view! as? UIButton {
// Inicia alteração
fieldInput.isHidden = false
// Acção associada a cada botão
selectedButton = button
}
}
}
}
He’s complaining about the view, I don’t know what’s wrong
Fábio, thanks for the code, but it didn’t work right, when I click on the button it’s not having any action, however I wanted to know the following, I’m a little confused, because I realized this project on Android and now I need to migrate it to Swift, however what happens, on Android, I have the button, when the user open it, opens a modal, we can say so, there is a field to insert value, after it insert and confirm the screen closes and the text inside the button is updated with the value typed, but I’m not able to reproduce it, neither need be 4 buttons, one already serves me
– Andre Cabral
@Andrecabral the rest of the settings were done in Interface Builder as I imagined you would have done. If you add this in viewDidLoad() my code should work for the first button:
let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressButton(sender:)))
 charOne.addGestureRecognizer(longPressGestureRecognizer)
– Fábio Salata