在第二个字符后添加“ /”符号

问题描述 投票:0回答:1

我有Xamarin TextInput。这是一种“ mm / yy”格式。我需要在第二个符号后插入/

我有这种方法可以在2个字符后添加/

private static string AppendAtPosition(string baseString, int position, string character)
{
    var sb = new StringBuilder(baseString);
    for (int i = position; i < sb.Length; i += (position + character.Length))
        sb.Insert(i, character);
    return sb.ToString();
}

而且我这样称呼它

ExpiresInput.EditingChanged += (object sender, EventArgs e) =>
{
    var creditcardyear = ExpiresInput.Text;

    if (creditcardyear.Length <= 2) return;
    if (creditcardyear.Length > 2)
    {
        ExpiresInput.Text = AppendAtPosition(creditcardyear, 2, "/");
    }
    if (creditcardyear.Length == 5) {
        return;
    }

但是例如,当我想插入22/12时,有这个。

enter image description here

我该如何解决?

c# xamarin xamarin.ios
1个回答
0
投票
ExpiresInput.EditingChanged += (object sender, EventArgs e) =>
{
    var currentText = ExpiresInput.Text;
    if (currentText.Length == 1)
        return;

    int strLength = currentText.Length;
    if (Char.IsDigit(currentText, strLength -1) && Char.IsDigit(currentText, strLength - 2))
      currentText = $"{currentText}/";
}

此代码在每两位数字后添加“ /”。确定没有在文本框中键入任何其他字符后,需要删除最后的“ /”。

© www.soinside.com 2019 - 2024. All rights reserved.