แก้ไข / อัปเดต: Xcode 11.4 • Swift 5.2
กรุณาตรวจสอบความคิดเห็นผ่านรหัส
เนื้อหาไฟล์IntegerField.swift :
import UIKit
class IntegerField: UITextField {
    // returns the textfield contents, removes non digit characters and converts the result to an integer value
    var value: Int { string.digits.integer ?? 0 }
    var maxValue: Int = 999_999_999
    private var lastValue: Int = 0
    override func willMove(toSuperview newSuperview: UIView?) {
        // adds a target to the textfield to monitor when the text changes
        addTarget(self, action: #selector(editingChanged), for: .editingChanged)
        // sets the keyboard type to digits only
        keyboardType = .numberPad
        // set the text alignment to right
        textAlignment = .right
        // sends an editingChanged action to force the textfield to be updated
        sendActions(for: .editingChanged)
    }
    // deletes the last digit of the text field
    override func deleteBackward() {
        // note that the field text property default value is an empty string so force unwrap its value is safe
        // note also that collection remove at requires a non empty collection which is true as well in this case so no need to check if the collection is not empty.
        text!.remove(at: text!.index(before: text!.endIndex))
        // sends an editingChanged action to force the textfield to be updated
        sendActions(for: .editingChanged)
    }
    @objc func editingChanged() {
        guard value <= maxValue else {
            text = Formatter.decimal.string(for: lastValue)
            return
        }
        // This will format the textfield respecting the user device locale and settings
        text = Formatter.decimal.string(for: value)
        print("Value:", value)
        lastValue = value
    }
}
คุณจะต้องเพิ่มส่วนขยายเหล่านั้นในโครงการของคุณด้วย:
ส่วนขยายเนื้อหาไฟล์UITextField.swift :
import UIKit
extension UITextField {
    var string: String { text ?? "" }
}
ส่วนขยายของ Formatter.swiftเนื้อหาไฟล์:
import Foundation
extension Formatter {
    static let decimal = NumberFormatter(numberStyle: .decimal)
}
ส่วนขยาย NumberFormatter.swiftเนื้อหาไฟล์:
import Foundation
extension NumberFormatter {
    convenience init(numberStyle: Style) {
        self.init()
        self.numberStyle = numberStyle
    }
}
ส่วนขยายเนื้อหาไฟล์StringProtocol.swift :
extension StringProtocol where Self: RangeReplaceableCollection {
    var digits: Self { filter(\.isWholeNumber) }
    var integer: Int? { Int(self) }
}
ตัวอย่างโครงการ
               
              
var answer1 = Int(txtBox1.text)