I am trying to have two non-editable UITextField
display name and age. I have an Edit UIBarButtonItem
in my Navigation Bar that I want to be able to trigger the UITextField
to be editable when that button is pressed.
In my Interface Builder, I have the User Interaction Enabled option unchecked for the two UITextFields. Do I need to add ageText.UserInteractionEnabled = true
? I'm at a loss here.
class UserProfileVC: UIViewController,
UITextFieldDelegate, UINavigationControllerDelegate {
@IBOutlet weak var infoBorder: UILabel!
@IBOutlet weak var nameText: UITextField!
@IBOutlet weak var ageText: UITextField!
var textFields:[UITextField] = []
@IBAction func editButton(sender: UIBarButtonItem) {
nameText.becomeFirstResponder()
ageText.becomeFirstResponder()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
var currentTextField = textFields[0]
if (currentTextField == textField) {
currentTextField = textFields[1]
currentTextField.becomeFirstResponder()
} else {
currentTextField.resignFirstResponder()
}
return true
}
}
Set the Boolean variable to false, which enables editing in the text field. When someone taps the Done button, isEditing becomes false. Set the Boolean variable to true, which disables editing in the text field.
Solution with the HTML readonly attribute The readonly attribute specifies that the value cannot be modified, although the user can still tab to it, highlight it, and copy the content.
Swift's Text views represent static, unselectable text by default, but you can change that using the . textSelection() modifier with the . enabled value. When text is selected, the user automatically gains access to the regular text actions such as Copy and Share.
Yes, you want to do
nameText.userInteractionEnabled = true
ageText.userInteractionEnabled = true
and possibly
nameText.becomeFirstResponder()
when the edit button gets pressed the first time. You will probably also want to change the "Edit" button do a "Done" button. When the user presses the done button, you'll want to make sure you disable user interaction and resign first responder for both text fields.
You should have a Bool Variable. Set it to 'false' then when the button is pressed you toggle it to 'true'. Depending on its state just run to different methods which essentially allows you to edit or not.
Something like this:
var editTextFieldToggle: Bool = false
@IBoutlet var textFieldToggle: UIButton!
@IBAction func textFieldToggle_Action(sender: UIButton){
editTextFieldToggle = !editTextFieldToggle //switches button ON/OFF
if editTextFieldToggle == true {
textFieldActive()
} else {
textFieldDeactive()
}
}
textFieldActive(){
//Turn things ON
nameText.enabled == true
ageText.enabled == true
}
textFieldDeactive(){ //Add anything else
//Turn things OFF
nameText.enabled == false
ageText.enabled == false
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With