LENLY-LAB

>>>>

ЧАСТЫЕ ВОПРОСЫ

SWIFTUI

SwiftUI: числовой TextFild с цифровой клавиатурой, форматированием и пользовательским видом шапки клавиатуры, с настройкой числа знаков после запятой

extension UITextField {

@objc func doneButtonTapped(button:UIBarButtonItem) -> Void {

self.resignFirstResponder()

}}

struct DecimalField : UIViewRepresentable {

@Binding var text: Double

var placeholder:String

var maxFractionDigits:Int

func makeUIView(context: Context) -> UITextField {

let textField =  UITextField()

textField.keyboardType = .decimalPad

textField.clearButtonMode = .whileEditing

textField.delegate = context.coordinator

textField.placeholder=placeholder

textField.text = String(text)

let customView = UIToolbar(frame: CGRect(x: 0, y: 0, width: 10, height: 28))

customView.backgroundColor = UIColor(.white)

let img = UIImage(systemName: "multiply.circle")

let button = UIButton(type: .system)

button.setImage(img, for: .normal)

button.setTitle(" DONE", for: .normal)

button.sizeToFit()

button.addTarget(self, action: #selector(textField.doneButtonTapped(button:)), for: .touchUpInside)

button.contentHorizontalAlignment = .leading

let doneButton = UIBarButtonItem(customView: button)

customView.items = [doneButton]

textField.inputAccessoryView = customView // <--- Here

return textField}

func updateUIView(_ uiView: UITextField, context: Context) {}

func makeCoordinator() -> DecimalField.Coordinator {Coordinator(parent: self)}

class Coordinator: NSObject, UITextFieldDelegate {var parent: DecimalField

init(parent: DecimalField) {self.parent = parent}

func textFieldDidChangeSelection(_ textField: UITextField){

let formatter = NumberFormatter()

formatter.locale = Locale.current

formatter.usesGroupingSeparator = true

formatter.numberStyle = .decimal

formatter.maximumFractionDigits = parent.maxFractionDigits

formatter.groupingSeparator = " "

let completeString = textField.text!.replacingOccurrences(of: formatter.groupingSeparator, with: "")

.replacingOccurrences(of: formatter.decimalSeparator, with: ".")

var a=0;var b=0;var c=0; for character in completeString {if String(character)=="."{a+=1}

if a>0{b=0; if c

let value = Double(completeString) ?? 0; parent.text = value

if c != 1&&b != 1 {let formattedNumber = formatter.string(from: NSNumber(value: value)) ?? "";

if value>0{textField.text = formattedNumber;}}

}}}


Как можно использовать:


struct Content: View {

@State private var inv:Double=9835000

var body: some View {

DecimalField(text: $invest,placeholder: "Инвестиция",maxFractionDigits:4)

.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 45)

.overlay(

RoundedRectangle(cornerRadius: 16)

.stroke(Color.blue, lineWidth: 4))

}}

Связаться с нами

Web-studio LENLY-LAB

Email: task@lenly-lab.ru

г. Москва