在没有 NumberFormatter 的情况下停止 TextField 中的字符重复 [英] Stop character repetition in TextField without NumberFormatter

查看:41
本文介绍了在没有 NumberFormatter 的情况下停止 TextField 中的字符重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如在文本字段中,我希望能够重复所有数字,但用户应该只能使用一次小数点.所以,用户不应该能够做:12...4";但应该只能做一次12.4".有什么特别的方法可以做到吗?是否可以在不使用 UIKit 的情况下使用 SwiftUI 来完成?

For example in a textfield I want to be able to repeat all numbers, but user should be able to use decimal point only once. So, the user should not be able to do: "12...4" but should only be able to do it once "12.4". Any particular way to do do it? Is it possible to do it with SwiftUI without using UIKit?

import SwiftUI
import Combine

struct TipsView: View {
    @State private var amount = ""
    
    var body: some View {
        NavigationView {
            Form {
                Section (header: Text("Amount")) {
                    HStack (spacing: 1) {
                        Text("£")
                        TextField("Amount", text: $amount)
                            .onReceive(Just(amount)) { _ in
                                
                            }
                    }
                }
            }
        }
    }
}

推荐答案

我使用了字符串分隔符将输入字符串分成两个不同的数组.意思是,一个数组包含小数点前的值,另一个数组包含小数点后的值.

I have used a String separator to separate the input string into two different arrays. Meaning, one array would contain values before the decimal point and the other would contain values after the decimal point.

import SwiftUI

struct DecimalView: View {
    @State private var amount = ""
    var body: some View {
        Form {
            Section(header: Text("Amount")) {
                HStack {
                    Text("£")
                    TextField("Enter amount", text: $amount)
                        .onChange(of: amount) { _ in
                            let filtered = amount.filter {"0123456789.".contains($0)}
                            
                            if filtered.contains(".") {
                                let splitted = filtered.split(separator: ".")
                                if splitted.count >= 2 {
                                    let preDecimal = String(splitted[0])
                                    let afterDecimal = String(splitted[1])
                                    amount = "\(preDecimal).\(afterDecimal)"
                                }
                            }
                        }
                }
            }
        }
    }
}

这篇关于在没有 NumberFormatter 的情况下停止 TextField 中的字符重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆