首页 > 解决方案 > Swift 4 - UITextField DidBeginEditing

问题描述

我有四个文本字段(PISARadius、aliasingVelocity、AIVMax 和 AIVTI)和两个 UIButton(calcEROAButton 和 regurgVolumeButton)。

我尝试仅在 PISARadius、aliasingVelocity 和 AIVMax 具有数字输入时启用 calcEROAButton,而当所有四个文本字段都输入时启用 regurgVolumeButton。

我使用以下代码取得了一些成功,但是当我清除其中一个文本字段时,有时按钮不会禁用。此外,在填充相关文本字段并且用户单击其他地方之前,这些按钮似乎不会启用/禁用。对这种情况有什么明确的补救措施吗?感谢任何输入!

@IBOutlet weak var PISARadius: UITextField!
@IBOutlet weak var aliasingVelocity: UITextField!
@IBOutlet weak var AIVMax: UITextField!
@IBOutlet weak var AIVTI: UITextField!
@IBOutlet weak var EROAAnswer: UILabel!
@IBOutlet weak var RegurgVolumeAnswer: UILabel!
@IBOutlet weak var calcEROAButton: UIButton!
@IBOutlet weak var regurgVolumeButton: UIButton!

@IBAction func calcEROA(_ sender: UIButton)
{
    EROAAnswer.text = String(Int(PISARadius.text!)! + Int(aliasingVelocity.text!)! + Int(AIVMax.text!)!)
}

@IBAction func calcRegurgVolume(_ sender: UIButton)
{
    RegurgVolumeAnswer.text = String(Int(PISARadius.text!)! + Int(aliasingVelocity.text!)! + Int(AIVMax.text!)! + Int(AIVTI.text!)!)
}

override func viewDidLoad()
{
    super.viewDidLoad()
    calcEROAButton.isEnabled = false
    regurgVolumeButton.isEnabled = false
    PISARadius.delegate = self
    aliasingVelocity.delegate = self
    AIVMax.delegate = self
    AIVTI.delegate = self

}

func textFieldDidBeginEditing(_ textField: UITextField) {

    if ((PISARadius.text?.isEmpty == true) || (aliasingVelocity.text?.isEmpty == true) || (AIVMax.text?.isEmpty == true)){
        if(AIVMax.text?.isEmpty == true)
        {
            self.regurgVolumeButton.isEnabled = false
        }
        self.calcEROAButton.isEnabled = false

    }

    if ((PISARadius.text?.isEmpty == false) && (aliasingVelocity.text?.isEmpty == false) && (AIVMax.text?.isEmpty == false) && (AIVTI.text?.isEmpty == false)){
        self.regurgVolumeButton.isEnabled = true

    }
    else if ((PISARadius.text?.isEmpty == false) && (aliasingVelocity.text?.isEmpty == false) && (AIVMax.text?.isEmpty == false)){
        self.calcEROAButton.isEnabled = true

    }
    return
}

标签: uibuttonuitextfield

解决方案


我认为如果您使用自定义方法来检测文本字段输入,它可能会解决您的问题。

  override func viewDidLoad()
    {
        super.viewDidLoad()
        calcEROAButton.isEnabled = false
        regurgVolumeButton.isEnabled = false
        PISARadius.delegate = self
        aliasingVelocity.delegate = self
        AIVMax.delegate = self
        AIVTI.delegate = self

    // Add this selector to each of your textfield
    self.your_Textfield.addTarget(self, action: #selector(self.textFieldDidChange(textField:)), for: .allEvents)

    }

    // Any of the textfield changes this method will trigger
    @objc func textFieldDidChange(textField: UITextField) {
        // Add your logic 
    }

推荐阅读