在SwiftUI中如何在textField的字符串中添加”连字符”

huangapple go评论82阅读模式
英文:

How to add "hyphen" in textField's string by SwiftUI

问题

我想在第3个字符后面加一个连字符。我想要改成这样。如果我在文本字段中输入 1111111,它会自动变成 111-1111

@State var postalCode = ""

TextField("邮政编码", text: $postalCode)
.onReceive(Just(postalCode)) { _ in
if postalCode.count > 8 {
postalCode = String(postalCode.prefix(8))
}
else if postalCode.count == 3{
postalCode = postalCode + "-"
}
}

但是上面的代码在删除以前的字符时不起作用。我的意思是,如果我发现错误的数字,我无法回到第3个字符之前。文本字段会粘在 111- 上。我无法操作它。

我找到了一个Swift Storyboard示例代码。

class CreateViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var deckCodeLabel: UITextField!

override func viewDidLoad() {
super.viewDidLoad()
deckCodeLabel.delegate = self
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if (string == "") { return true }
if (textField.text?.count == 3) {
textField.text = (textField.text)! + string + "-"
return false
}

textField.text = String(textField.text!.prefix(8))
return true
}

但是我不知道如何将它改成SwiftUI中的代码。

英文:

I want to add hyphen after 3rd character.
I want to change like this.
If I input 1111111 in textfield, it automatically change to 111-1111

@State var postalCode = ""

TextField("PostalCode", text: $postalCode)
             .onReceive(Just(postalCode)) { _ in
                 if postalCode.count > 8 {
                       postalCode = String(postalCode.prefix(8))
                  }
                  else if postalCode.count == 3{
                       postalCode = postalCode + "-"
                  }
               }

But this above code doesn't work when I delete the previous characters.
I mean if I find wrong number, I can't go back before 3rd character.
The textfield sticks to 111-. I could not manipulate it.

And I found a swift storyboard sample code.

class CreateViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var deckCodeLabel: UITextField!
 
    
     override func viewDidLoad() {
       super.viewDidLoad()
       deckCodeLabel.delegate = self
   }
   
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
       if (string == "") { return true }
       if (textField.text?.count == 3) {
           textField.text = (textField.text)! + string + "-"
           return false
       }

       textField.text = String(textField.text!.prefix(8))
       return true
   }

But I don't know how to change it to my code in SwiftUI

答案1

得分: 1

你可以尝试这样做:

TextField("邮政编码", text: $postalCode)
    .onChange(of: postalCode) { _ in
        var withoutHyphen = String(postalCode.replacingOccurrences(of: "-", with: "").prefix(8))
        if withoutHyphen.count > 3 {
            withoutHyphen.insert("-", at: postalCode.index(postalCode.startIndex, offsetBy: 3))
            postalCode = withoutHyphen
        } else {
            postalCode = withoutHyphen
        }
    }
英文:

You can try this:

TextField("PostalCode", text: $postalCode)
	.onChange(of: postalCode) { _ in
		var withoutHyphen = String(postalCode.replacingOccurrences(of: "-", with: "").prefix(8))
		if withoutHyphen.count > 3 {
			withoutHyphen.insert("-", at: postalCode.index(postalCode.startIndex, offsetBy: 3))
			postalCode = withoutHyphen
		} else {
			postalCode = withoutHyphen
		}
	}

答案2

得分: 0

  • 如果用户输入“123”,保持不变为“123”。
  • 如果用户输入“1234”,将其更改为“123-4”。
  • 如果用户输入“123-”,保持不变为“123-”。
  • 如果用户输入“123-”然后按退格键,TextField会删除“-”,你也应该保持删除。
struct TestView: View {
    @State var postalCode = ""
    
    var body: some View {
        TextField("邮政编码", text: $postalCode)
            .onChange(of: postalCode) { _ in
                groomCode()
            }
    }
    
    private func groomCode() {
        var groomed = ""
        for c in postalCode {
            if c == "-" && groomed.count == 3 {
                // 复制在正确位置的连字符。
                groomed.append(c)
            } else if c.isASCII && c.isNumber {
                if groomed.count == 3 {
                    // 在第4位数字前插入连字符。
                    groomed.append("-")
                }
                // 复制数字。
                groomed.append(c)
            } 
            if groomed.count == 8 {
                break
            }
        }
        postalCode = groomed
    }
}
英文:

One way to handle this is to insert the hyphen only if there are more than three digits, or if it’s already there in the correct place. So:

  • If the user types “123”, you leave it as “123”.
  • If the user types “1234”, you change it to “123-4”.
  • If the user types “123-“, you leave it as “123-“.
  • If the user types “123-“ and then backspace, the TextField removes the - and you leave it removed.
struct TestView: View {
    @State var postalCode = ""
    
    var body: some View {
        TextField("Postal Code", text: $postalCode)
            .onChange(of: postalCode) { _ in
                groomCode()
            }
    }
    
    private func groomCode() {
        var groomed = ""
        for c in postalCode {
            if c == "-" && groomed.count == 3 {
                // Copy over the hyphen that was in the correct place.
                groomed.append(c)
            } else if c.isASCII && c.isNumber {
                if groomed.count == 3 {
                    // Insert a hyphen before the 4th digit.
                    groomed.append("-")
                }
                // Copy over the digit.
                groomed.append(c)
            } 
            if groomed.count == 8 {
                break
            }
        }
        postalCode = groomed
    }
}

huangapple
  • 本文由 发表于 2023年3月7日 21:21:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75662512.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定