2015-05-13 19 views
5

Quindi il mio concetto è semplice, ho un campo di testo e un pulsante con l'etichetta "Avanti". Vorrei che il pulsante Avanti fosse disabilitato per gli utenti se non hanno inserito nulla nel campo di testo. Per fare questo, ho eseguito questo codice:Imposta un UIButton inattivo se non viene immesso alcun testo in un campo di testo in Swift

@IBAction func nextButton(sender: UIButton) { 

    if textField.text.isEmpty { 

     buttonLabel.userInteractionEnabled = false 

    } 
} 

Ciò disabilita il tasto come voglio, ma il problema è, se il testo viene poi immesso nel campo di testo, il pulsante è ancora disattivato. Ho provato ad aggiungere la frase "else" dopo l'istruzione "if" per invertire ciò che sto dicendo per vedere se funziona, ma non è così.

Qualsiasi aiuto molto apprezzato.

Nick

mio codice:

import UIKit 

class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate { 

func imageEffect() { 

    // Set vertical effect for background 
    var verticalMotionEffect : UIInterpolatingMotionEffect = 
    UIInterpolatingMotionEffect(keyPath: "center.y", 
     type: .TiltAlongVerticalAxis) 
    verticalMotionEffect.minimumRelativeValue = -20 
    verticalMotionEffect.maximumRelativeValue = 20 

    // Set horizontal effect for background 
    var horizontalMotionEffect : UIInterpolatingMotionEffect = 
    UIInterpolatingMotionEffect(keyPath: "center.x", 
     type: .TiltAlongHorizontalAxis) 
    horizontalMotionEffect.minimumRelativeValue = -20 
    horizontalMotionEffect.maximumRelativeValue = 20 

    // Create group for background to combine both 
    var group : UIMotionEffectGroup = UIMotionEffectGroup() 
    group.motionEffects = [horizontalMotionEffect, verticalMotionEffect] 

    // Add both effects to your view for background 
    myBackgroundView.addMotionEffect(group) 

} 

var datePickerView:UIDatePicker = UIDatePicker() 

@IBAction func textFieldEdited(sender: UITextField) { 

    var datePickerView : UIDatePicker = UIDatePicker() 
    datePickerView.datePickerMode = UIDatePickerMode.Date 
    sender.inputView = datePickerView 
    datePickerView.addTarget(self, action: Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged) 

    } 

func handleDatePicker(sender: UIDatePicker) { 
    var dateFormatter = NSDateFormatter() 
    dateFormatter.dateFormat = "dd MMMM yyyy" 
    questionTextField.text = dateFormatter.stringFromDate(sender.date) 
} 

var countryData = ["United Kingdom", "France", "Spain", "Germany", "Berlin", "Eygpt", "United States"] 

var pickerView:UIPickerView = UIPickerView() 

@IBOutlet var progressStatus: UIProgressView! 

@IBOutlet var barImage: UIImageView! 

@IBOutlet var questionLabel: UILabel! 

@IBOutlet var buttonBarImage: UIImageView! 

@IBOutlet var buttonLabel: UIButton! 

@IBOutlet var myBackgroundView: UIImageView! 

@IBOutlet var questionTextField: UITextField! 

let questions = ["Where are you going?", "What are you doing there?", "When do you go?"] 

var currentQuestionIndex = 0 

let placeholder = ["Country", "Activity", "Date"] 

var currentPlaceholderIndex = 0 

@IBAction func nextButton(sender: AnyObject) { 

    if currentQuestionIndex == 0 { 

     progressStatus.setProgress(0.333, animated: true) 

    } else if currentQuestionIndex == 1 { 

     progressStatus.setProgress(0.666, animated: true) 

    } else { 

     progressStatus.setProgress(1, animated: true) 

    } 

    // Initial setup on button press 
    questionTextField.hidden = false 
    barImage.hidden = false 
    questionTextField.placeholder = placeholder[currentPlaceholderIndex] 
    questionLabel.text = questions[currentQuestionIndex] 
    questionTextField.resignFirstResponder() 

    // Reset text field to have no text 
    questionTextField.text = "" 

    // Displays the questions in array and displays the placeholder text in the textfield 
    if currentQuestionIndex <= questions.count && currentPlaceholderIndex <= placeholder.count { 

     currentQuestionIndex++ 
     currentPlaceholderIndex++ 
     //progressStatus.setProgress(0.333, animated: true) 
     buttonLabel.setTitle("Next", forState: UIControlState.Normal) 


     // Animate text for questionLabel 
     UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.5, options: nil, animations: { 

      self.questionLabel.center = CGPoint(x: -110 , y: 305 + 20) 

      }, completion: nil) 

    } else { 

     //Add some logic here to run whenever the user has answered all the questions. 

    } 

} 


override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

    questionTextField.delegate = self 
    pickerView.delegate = self 
    pickerView.dataSource = self 

    // Applies the image effect to the image in myBackgroundImage 
    imageEffect() 

    // Sets the button text 
    buttonLabel.setTitle("Get started", forState: UIControlState.Normal) 

    // Sets the question text to be blank 
    questionLabel.text = "" 


    // Sets placeholder text in the text field 
    questionTextField.placeholder = "" 

    // Hides the text field 
    questionTextField.hidden = true 

    // Hides the image background for the text field 
    barImage.hidden = true 

    // Sets the progress bar to nil 
    progressStatus.setProgress(0, animated: true) 

    if questionTextField.text.isEmpty { 

     buttonLabel.userInteractionEnabled = false 
    } 

} 

func textFieldDidBeginEditing(textField: UITextField) { 


    buttonLabel.userInteractionEnabled = true 


    switch currentQuestionIndex { 

    case 0: 
     // TODO: Add UIPickerView 
     self.view.addSubview(datePickerView) 
    case 2: 
     // TODO: Add UIDatePicker 
     self.view.addSubview(datePickerView) 

    default: 
     println("default") 
    } 
} 


// resigns the keyboard when user presses the return/next key on keyboard 

func textFieldShouldReturn(textField: UITextField) -> Bool { 

    questionTextField.resignFirstResponder() 

    return true 

} 

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { 

    return 1 
} 

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { 

    return countryData.count 

} 

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { 
    return countryData[row] 

} 

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { 

    questionTextField.text = countryData[row] 
    pickerView.hidden = true 

} 




// Resigns the keyboard if the user presses anywhere on the screen 
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { 

    self.view.endEditing(true) 
} 


override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

} 

risposta

3

Edit:

Set myButton.userInteractionEnabled = false nel viewDidLoad o viewWillAppear.

Imposta il tuo textField 's delegate.

e poi

func textFieldDidBeginEditing(textField: UITextField) { 
    if !textField.text.isEmpty 
     myButton.enable = true 

    } else { 
     buttonLabel.enable = false 
    } 
} 
+0

Ciao, ho provato, ma non funziona, mantiene il pulsante disabilitato. – Nick89

+0

Scusa se ho perso il contesto, controlla la modifica. Considera anche il .enable then .userInteractionEnabled per forzare la modifica dell'alfa e far sapere all'utente che è disabilitato. –

2

È necessario impostare la VC come TextFieldDelegate. Quindi puoi reagire sullo stato dei campi di testo. Guarda questo piccolo esempio:

class ViewController: UIViewController, UITextFieldDelegate { 

    @IBOutlet weak var myTextField: UITextField! 
    @IBOutlet weak var myButton: UIButton! 

    override func viewDidLoad() { 
    super.viewDidLoad() 

    // Set the delegate of your textField to this class 
    myTextField.delegate = self 

    if myTextField.text.isEmpty { 
     myButton.userInteractionEnabled = false 
    } 
    } 
    // This method is available, because this class is now the delegate 
    func textFieldDidBeginEditing(textField: UITextField) { 
    myButton.userInteractionEnabled = true 
    } 
} 

Questo dovrebbe essere abbastanza simile al tuo VC.

Si prega di notare la prima riga, dove viene detto al VC di conformarsi al TextFieldDelegate Protocol.

+0

Hi @gutenmorgenuhu. In realtà condivido il campo di testo per 3 domande che vengono popolate da un array. Ogni volta che l'utente preme il pulsante Avanti, viene visualizzata la domanda successiva e il campo di testo si reimposta. Ho aggiunto il tuo codice come hai detto tu, e ha funzionato, ma solo per la prima volta. Ha senso? – Nick89

+0

Quindi è necessario scrivere una logica più elaborata che tenga traccia del campo di testo da cui si stanno raccogliendo dati, e rendere il metodo textFieldDidBeginEditing abilitare solo il pulsante successivo in base al campo di testo specificato nel parametro textField. –

+0

Questo è il nucleo o la programmazione - capire come applicare gli strumenti del linguaggio per creare un comportamento nuovo di zecca. –

1

Il codice dovrebbe essere qualcosa di simile come qui di seguito, Supponendo pulsante Avanti deve essere attivata solo quando abbiamo il testo in un campo di testo altro è necessario modificare la logica conseguenza.

class ViewController: UIViewController, UITextFieldDelegate { 

@IBOutlet weak var textField1: UITextField! 
@IBOutlet weak var textField2: UITextField! 
@IBOutlet weak var textField3: UITextField! 
@IBOutlet weak var nextButton: UIButton! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    nextButton.userInteractionEnabled = false 
    textField1.delegate = self 
    textField2.delegate = self 
    textField3.delegate = self 
} 
@IBAction func NextButtonAction(sender: UIButton) 
{ 
    println("Next Button Tapped") 
} 
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { 
    if textField == textField1 
    { 
     var oldStr = textField1.text as NSString 
     var newStr = oldStr.stringByReplacingCharactersInRange(range, withString: string) as NSString 
     if newStr.length == 0 
     { 
      nextButton.userInteractionEnabled = false 
     }else 
     { 
      nextButton.userInteractionEnabled = true 
     } 
    } 
    return true 
} 
} 
+0

Grazie per la tua risposta prima di tutto. Il fatto è che ho solo 1 campo di testo che è condiviso tra le 3 domande. Quindi, come posso cambiare quanto sopra per farlo funzionare con un solo campo di testo? Grazie in anticipo – Nick89

+0

Puoi fornire il codice su come condividere lo stesso campo di testo per 3 domande, in modo che possiamo aiutarti? –

+0

Ho aggiunto il mio codice qui sopra. Mi sono conformato a UITextfieldDelegate e ho impostato il delegato su = self in ViewDidLoad. – Nick89

0

evento dovrebbe rispondere al montaggio cambiato, versione Swift

@IBAction func editingChanged(textfield: UITextField) { 

     myButton.enabled = textfield.text?.characters.count > 0 
}