使用阿拉伯语键盘输入TextField数字

时间:2016-08-08 09:40:42

标签: swift input int uitextfield arabic

我们的应用程序中使用少量输入,使用数字键盘类型的键盘。我们将这些值存储为Int。

几天前,我们遇到了一个使用阿拉伯语键盘的应用用户的错误。当尝试将输入保存到数据库时,我们遇到错误,因为输入是阿拉伯语符号,并且不会被识别为Int。

我想知道你们是如何解决这类问题的。我正在考虑像这样转换输入值,所以我为String类创建了一个小扩展:

class XmlReader {

    void read()
    {
        string typeReadFromXML;
        vector<double> coordinates;
        Point* pt = newPoint(typeReadFromXML, coordinates);

        // OR
        //string typeReadFromXML;
        //PointType type= XMLReader::conversion(typeReadFromXML);
        //vector<double> coordinates;
        //Point* pt = newPoint(type, coordinates);
    }
};

class Point {

    Point(string type, vector<double> v)
    {
        _type = conversion(type);
    }

    Point(PointType type, vector<double> v)
    {
        _type = type;
    }

private:
    enum PointType {
        type1,
        type2
    };

    PointType conversion(string){}

    PointType _type;
    vector<double> _coords;
};

还有其他更好的方法吗?

1 个答案:

答案 0 :(得分:2)

我使用下面的代码将阿拉伯数字“1234567890”转换为英文数字“1234567890”我将值返回为字符串,所以这可能就是差异。

如果仍需要返回Int值,请尝试更改代码:

let returnNumber = Int(number!)

if Int(number!) != nil {
 return Int(number!)
}
else{
 return -1 //here you can return a value that you can check to decide    if an error happen or no.
}

这是我的工作代码:

extension String {
func arabicNumberToEnglish() -> String{

    //if number start with zero then Formatter.number(from: self) will remove it, 
   //so we need to know how many leading zero contain in the string 
   //so that we can add them before the return
    var leadingZero: String = ""

    func getLeadingZero(_ value: String)
    {

        if value.hasPrefix("0") || value.hasPrefix("٠") {
            leadingZero = leadingZero + "0"
            var newValue = value
            newValue = String(newValue.characters.dropFirst())
            getLeadingZero(newValue)
        }
        else{
            return
        }


    }

    //calling the inline function to get the leading zeros count
    getLeadingZero(self)

    let Formatter: NumberFormatter = NumberFormatter()
    Formatter.locale = NSLocale(localeIdentifier: "EN") as Locale!
    if let final = Formatter.number(from: self){
        // returning the final result after adding the leadingZero's to it.
        return leadingZero + "\(final)"

    }
    else{
        return self
    }

}

}
相关问题