如何检查UITextField中的值是否是介于1-100之间的数字间隔,以及该数字是否在该间隔内以将值发送到另一个UIViewController?如果该值不在该间隔内,则显示警报。
我的另一个控制器有一个var receivedValue = ""我将使用它来填充UILabel。
这是我的代码:

import UIKit

class ChildViewController: UIViewController {
    @IBOutlet weak var insertNumberTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        insertNumberTextField.delegate = self
    }

    @IBAction func checkNumberIntervalButton(_ sender: UIButton) {
        if insertNumberTextField.text == "\(1..<100)"{
            print("Number is in interval 1 - 100.")

            navigationController?.popViewController(animated: true)

            dismiss(animated: true, completion: nil)
        } else {
            let alert = UIAlertController(title: "Try again", message: "Sorry but this numer is not in the inverval 1 - 100. Try again.", preferredStyle: .alert)

            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))

            present(alert, animated: true, completion: nil)

            insertNumberTextField.text = ""

            print("Number is not in the inverval 1 - 100.")
        }
    }
}

extension ChildViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let allowedCharacters = CharacterSet.decimalDigits
        let characterSet = CharacterSet(charactersIn: string)
        return allowedCharacters.isSuperset(of: characterSet)
    }
}

最佳答案

将文本字段的文本转换为Int并进行比较。

if let text = insertNumberTextField.text, let value = Int(text), (0 ..< 100).contains(value) {
    // number is between 1 and 100
} else {
    // show alert
}

关于ios - 检查UITextfield的数字间隔,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50749688/

10-13 09:21