2014-11-17 3 views
1

У меня есть кнопка, которая отключена в моем контроллере. У меня есть IBActions, когда редактируются два текстовых поля. Я пытаюсь включить кнопку, когда два текстовых поля содержат целые числа. Я пытался это сделать, но всякий раз, когда я запускаю симулятор ios, кнопка остается отключенной, даже когда я помещаю целые числа в каждое текстовое поле. Почему он остается инвалидом? Я новичок в быстром, поэтому, пожалуйста, помогите мне. Вот код для всего моего проекта:Swift: кнопка включения не работает?

import UIKit 

class ViewController: UIViewController, UITextFieldDelegate { 

@IBOutlet weak var calculatorButton: UIButton! 
@IBOutlet weak var inspirationLabel: UILabel! 
@IBOutlet weak var beginningLabel: UILabel! 
@IBOutlet weak var calculatorContainer: UIView! 
@IBOutlet weak var answer1Label: UILabel! 
@IBOutlet weak var doneButton: UIButton! 
@IBOutlet weak var yourWeightTextField: UITextField! 
@IBOutlet weak var calorieNumberTextField: UITextField! 
@IBOutlet weak var menuExampleButton: UIButton! 
@IBOutlet weak var aboutButton: UIButton! 
@IBOutlet weak var calculateButton: UIButton! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib 
    yourWeightTextField.delegate = self 
    calorieNumberTextField.delegate = self 
    calculateButton.enabled = false 
} 

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

@IBAction func calculatorButtonTapped(sender: AnyObject) { 
    calculatorContainer.hidden = false 
    inspirationLabel.hidden = true 
    beginningLabel.hidden = true 
    menuExampleButton.hidden = true 
    aboutButton.hidden = true 
} 

@IBAction func yourWeightEditingDidEnd(sender: AnyObject) { 
    yourWeightTextField.resignFirstResponder() 
} 

@IBAction func calorieNumberEditingDidEnd(sender: AnyObject) { 
    calorieNumberTextField.resignFirstResponder() 
} 

var yourWeightFilled = false 
var calorieNumberFilled = false 

func yourWeightTextFieldValueValidInt(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { 
    // Find out what the text field will be after adding the current edit 
    let text = (yourWeightTextField.text as NSString).stringByReplacingCharactersInRange(range, withString: string) 

    if let intVal = text.toInt() { 
     self.yourWeightFilled = true 
    } else { 
     self.yourWeightFilled = false 
    } 
    return true 
} 
func calorieNumberTextFieldValueValidInt(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { 
    // Find out what the text field will be after adding the current edit 
    let text = (calorieNumberTextField.text as NSString).stringByReplacingCharactersInRange(range, withString: string) 

    if let intVal = text.toInt() { 
     self.calorieNumberFilled = true 
    } else { 
     self.calorieNumberFilled = false 
    } 
    return true 
} 

@IBAction func yourWeightTextFieldEdited(sender: AnyObject) { 
    if self.yourWeightFilled && self.calorieNumberFilled { 
     self.calculateButton.enabled = true 
    } 
} 

@IBAction func calorieNumberTextFieldEdited(sender: AnyObject) { 
    if self.yourWeightFilled && self.calorieNumberFilled { 
     self.calculateButton.enabled = true 
    } 
} 

}

ответ

0

Ваши методы делегата немного перепутали - они должны быть названы именно то, что ожидает, что абонент, или они не будут найдены, поэтому yourWeightTextFieldValueValidInt() и calorieNumberTextFieldValueValidInt() вообще не вызываются. Вместо этого вам нужно обрабатывать изменения в обоих текстовых полей в одном методе:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { 
    // Find out what the text field will be after adding the current edit 
    let text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string) 

    if textField == yourWeightTextField { 
     yourWeightFilled = text.toInt() != nil 
    } else if textField == calorieNumberTextField { 
     calorieNumberFilled = text.toInt() != nil 
    } 

    return true 
} 
+0

Хорошо, что делает гораздо больше смысла. Спасибо! –

Смежные вопросы