如何在文本字段中添加或删除前缀为“减号”的符号?

时间:2019-04-03 08:42:03

标签: ios swift uitextfield

我想在文本字段中添加或删除带前缀的减号。该按钮应像切换按钮一样。

我编写了一个函数来检查文本字段是否已带有减号。如果不加一个。如果已经有一个,则将其删除。

protocol KeyboardDelegate {
    func toggleMinus(_ character: String)
}

class KeyboardViewController: UIInputViewController {


    var delegate: KeyboardDelegate?

    override func updateViewConstraints() {
        super.updateViewConstraints()

        // Add custom view sizing constraints here
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let nib = UINib(nibName: "NumpadView", bundle: nil)
        let objects = nib.instantiate(withOwner: self, options: nil)

        view = objects[0] as! UIView

        // Perform custom UI setup here
    }
       // Toggle minus button action function of custom keyboard
       @IBAction func negateButtonPressed(_ sender: UIButton) {
        var string = sender.titleLabel?.text
        self.delegate?.toggleMinus(string!)
    }

}
class TemperatureViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textCelcius: UITextField!
    @IBOutlet weak var textFahrenheit: UITextField!
    @IBOutlet weak var textKelvin: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()

        textCelcius.delegate = self
        textFahrenheit.delegate = self
        textKelvin.delegate = self
    }

    func toggleMinus(_ character: String) {
        if var text = textCelcius.text , text.isEmpty == false{
            textCelcius.insertText(character)

            if text.hasPrefix("-") {
                text = text.replacingOccurrences(of: "-", with: "")
            } else {
                text = "-\(text)"
            }

            textCelcius.text = text
        }
    }
}

我希望文本字段的前缀值更改为减号,或者在用户按下自定义键盘上的按钮时将其删除(如果已有的话)。现在,当我按下键盘上的按钮时,什么也没有发生。我认为我没有从toggleMinus()类中正确调用TemperatureViewController中的KeyboardViewController函数,或者toggleMinus()函数中存在逻辑错误。

0 个答案:

没有答案