Advertisement
Guest User

Untitled

a guest
Dec 29th, 2021
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.05 KB | None | 0 0
  1. //
  2. //  TestSheetKeyboard.swift
  3. //  toushare
  4. //
  5. //  Created by James Mallison on 27/12/2021.
  6. //
  7.  
  8. import SwiftUI
  9.  
  10. struct TestKeyboard: View {
  11. //   @State var showingSheet = false
  12.     @State var str: String = ""
  13.     @State var num: Float = 1.2
  14. ////
  15.     @FocusState private var focusedField: Field?
  16.     private enum Field: Int, CaseIterable {
  17.         case amount
  18.         case str
  19.     }
  20. //
  21.     var body: some View {
  22.         VStack {
  23.             Spacer()
  24.  
  25.             TextField("A text field here", text: $str)
  26.                 .focused($focusedField, equals: .str)
  27.  
  28.             TestTextField(value: $num)
  29.                 .focused($focusedField, equals: .amount)
  30.            
  31.             Text("HELLO WORLD")
  32.            
  33.             Spacer()
  34.         }
  35.     }
  36.  
  37. }
  38.  
  39.  
  40. struct TestKeyboard_Previews: PreviewProvider {
  41.     static var previews: some View {
  42.         TestKeyboard()
  43.     }
  44. }
  45.  
  46. // This is what I took and slightly modified to work with Floats.
  47. // Maybe not the best way using String(value). There's no Formatter use working here either...
  48. struct TestTextField: UIViewRepresentable {
  49.     @Binding var value: Float
  50.    
  51.     var keyType: UIKeyboardType = .decimalPad
  52.     var formatter: Formatter = FloatNumberFormatter()
  53.    
  54.     func makeUIView(context: Context) -> UITextField {
  55.         let textfield = UITextField()
  56.        
  57.       textfield.keyboardType = keyType
  58.         let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: textfield.frame.size.width, height: 44))
  59.         let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(textfield.doneButtonTapped(button:)))
  60.         toolBar.items = [doneButton]
  61.         toolBar.setItems([doneButton], animated: true)
  62.         textfield.inputAccessoryView = toolBar
  63.         return textfield
  64.     }
  65.    
  66.     func updateUIView(_ uiView: UITextField, context: Context) {
  67.         uiView.text = String(value)
  68.     }
  69. }
  70.  
  71. extension  UITextField{
  72.     @objc func doneButtonTapped(button:UIBarButtonItem) -> Void {
  73.        self.resignFirstResponder()
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement