在SwiftUI中向TextField添加前缀

7
我希望在文本框中有一个不能被删除的“+”符号。用户应该能够在其后输入值,如果按回退键,它只能删除用户输入的值。当我输入其他数字时,它将自动在输入值的开头添加一个“+”。
例如:我想在文本框中添加国家代码,因此只要用户开始输入国家代码,就会自动在字段开头添加“+”。

这里可能会有些混淆,请澄清一下,您需要在model值中也添加'+',还是只在TextFiled UI中添加? - Asperi
6个回答

5
在 SwiftUI 中,您可能希望使用 Combine 框架来处理此操作。创建一个 ObservableObject 来处理值的变化。以下是示例代码:
import SwiftUI
import Combine

struct ContentView: View {

    class ViewModel: ObservableObject {
        @Published var text = "" {
            didSet {
                if text.prefix(1) != "+" {
                    text = "+" + text
                }
            }
        }
    }

    @ObservedObject var viewModel = ViewModel()

    var body: some View {
        TextField("Placeholder", text:$viewModel.text)
    }
}

1
比UIViewRepresentable还要好!完美! - Chris
它的工作正常,但当我删除“+”然后写一些东西时,“+”会移到文本后面,这不好! - Ravindra_Bhati
那么你必须更新你的问题。此外,正如@Chris所提到的,这不是一个“我们为您编码”的平台。您需要展示一些努力并说明您已经尝试过什么。 - Bijoy Thangaraj

0

尝试用我的“千克”替换“+”

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        var amountTypedString = myTF.text
        if string.count > 0 {
            if amountTypedString?.count ?? 0 > 2 {
                amountTypedString = String((amountTypedString?.dropLast(2))!)
            }
            amountTypedString! += string
            let newString = amountTypedString! + "kg"
            myTF.text = newString
        } else {
            amountTypedString = String((amountTypedString?.dropLast(3))!)
            if (amountTypedString?.count)! > 0 {
                let newString = amountTypedString! + "kg"
                myTF.text = newString
            } else {
                myTF.text = ""
            }
        }
        return false
    }

0

我在我的应用程序中需要相同的功能(用户需要输入国家代码,以便我可以验证号码),并且我使用自定义绑定实现了类似于您想要的功能:

struct PrefixedTextField: View {
    @State private var countryCode = "+"

    var body: some View {
        let countryCodeCustomBinding =
            Binding(
                get: { self.countryCode },
                set: {
                    self.countryCode = $0
                    if self.countryCode.isEmpty { self.countryCode = "+" }
                })

        return TextField("+91", text: countryCodeCustomBinding).keyboardType(.numberPad)
    }
}

0
通常你应该在这里发布你的编程尝试,因为这不是一个“我们为你编码”的平台...但是...今天是个晴天,所以这是代码 ;)
override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let textField = UITextField(frame: CGRect(x: 100, y: 100, width: 200, height: 20))
        view.addSubview(textField)

        textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: UIControl.Event.editingChanged)

        textField.layer.borderColor = UIColor.red.cgColor
        textField.layer.borderWidth = 2

    }

    @objc func textFieldDidChange(_ textField: UITextField) {

        if textField.text?.prefix(1) != "+" {
            textField.text = "+" + textField.text!
        }
    }

是的✌,它是在Swift版本(3、4、5)中编写的,但在SwiftUI中会怎样呢? - Ravindra_Bhati
1
编写一个 UIViewRepresentable,用于 UITextfield,并使用上面的代码。 - Chris

0
  import SwiftUI

struct ContentView: View {

    @State var userName : String = ""
    var body: some View {
        VStack {
            HStack{
                Image(systemName: "plus")
                TextField("placeholder",text:$userName)
            }
            .padding(5)
            .foregroundColor(.white)
            .background(Capsule().fill(Color.gray))
            Spacer()
        }.padding(5)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

我认为这是一种更好的方法,可以添加“+”号,这样当您访问 userName 时就不会收到 + 号了。


这是一个很好的设计。但问题明确要求在文本字段中使用“+”符号。 - Bijoy Thangaraj
我需要在编辑时添加 '+',并且我必须使用 TextField 的相同值与 Web 服务进行通信。 - Ravindra_Bhati

0
这是可用的代码:

import SwiftUI import Combine

class ViewModel: ObservableObject {
    @Published var text = "" {
        didSet {
            if text.prefix(1) != "+"{
            if text.count == 1{
                text = "+" + amount
            }
        }
        if text.prefix(0) == "+" && text.prefix(1) == ""{
            text = ""
        }
    }
}

@ObservedObject var viewModel = ViewModel()

var body: some View {
    TextField("Placeholder", text:$viewModel.text)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接