ios - 为什么我的 Swift 代码函数只运行一次?

标签 ios swift xcode ibaction iboutlet

所以我是编程新手,我正在做一个 Swift 税务计算器学习练习。目前,我只是想在开始计算之前设置一些东西。

我试图让代码接受文本输入,将其插入字符串并在 TextView 中打印。

到目前为止,我的代码工作了一次,但从那以后它似乎停止工作了。我基本上只是希望我的代码在用户点击第一个输入文本字段时自行重置。

我试过将 TextView 设置为“”,但这似乎不起作用。它只是插入“”,这不是我想要的。

这是我的代码:

class ViewController: UIViewController {

    @IBOutlet weak var income: UITextField!

    @IBOutlet weak var takeHomePay: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        income.delegate = self
        // Do any additional setup after loading the view.

    }

    @IBAction func calculateTapped(_ sender: Any) {
        if takeHomePay.text.isEmpty {
        takeHomePay.text = "You are earning $\(income.text!)"
        } else if !takeHomePay.text.isEmpty {
            takeHomePay.text = "You need to enter a figure"
        } else {
            takeHomePay.text = "ERROR"
        }

    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        income.resignFirstResponder()
    }

}

extension ViewController : UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

}

为什么我的函数只运行一次?每次更改输入时,我都希望看到输出发生变化。可能是一个简单的修复,但正如我所说,我只是在学习。

帮助将不胜感激!

最佳答案

将委托(delegate)添加到 viewDidLoad 中的 textView

takeHomePay.delegate = self

然后实现

func textViewDidChange(_ textView: UITextView) {
        if takeHomePay.text.isEmpty {
        takeHomePay.text = "You are earning $\(income.text!)"
        } else {
            takeHomePay.text = "You need to enter a figure"
        } 
}

由于 textView 为空或不为空,无法到达最底部


class VCName:UIViewController,UITextViewDelegate{}

关于ios - 为什么我的 Swift 代码函数只运行一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57757103/

相关文章:

ios - 函数 'AudioServicesPlaySystemSoundWithVibration'的隐式声明在c99中无效

ios - 线程 8 : Signal SIGABRT When performing a segue

objective-c - 核心数据以编程方式向条目添加属性

ios - Swift 计算器运算符问题

iOS 11 导航栏显得比应有的小

objective-c - Swift 类使用 Objective-C 类使用 Swift 类

ios - 当我从 View 返回时,标签栏不显示

objective-c - 如何在 XCode 中将自定义 UIButton 添加到 nib 文件?

ios - 即使已设置图像,也不会在 UIImageView 中显示图像

ios - iPad 版 iOS App