LiYanan2004

前言

swiftUI 中的 TextField 模块对中文的支持并不是很好,且功能不够强大,这篇博客提供了从 UIKit 中移植过来的功能更为强大的 UITextField。

你可以增加 “键盘震动反馈” 或是 “实时字数统计” 等功能,并可以在 swiftUI 中获得更好的语言兼容性

兼容模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import SwiftUI
import UIKit

struct UIKitTextField: UIViewRepresentable {
@State var placeHolder: String
@State var type: UIKeyboardType
@State var border: UITextField.BorderStyle = .none
@Binding var Text: String

func makeCoordinator() -> UIKitTextField.Coordinator {
return Coordinator(text: $Text)
}

class Coordinator: NSObject, UITextFieldDelegate {
@Binding var text: String
init(text: Binding<String>) {
_text = text
}
@objc func textFieldEditingChanged(_ sender: UITextField) {
// This method is called when the text changes.
// You can add some features like: Haptic Touch, Words Count, etc...
// use "sender.text" to detect the text in the UITextField
self.text = sender.text ?? "" // Updating Variable
}

@objc func textFieldDown(_ sender: UITextField) {
sender.endEditing(true) // Exit
}
}

func makeUIView(context: Context) -> UITextField {
let myTextField = UITextField()
myTextField.addTarget(context.coordinator, action: #selector(Coordinator.textFieldEditingChanged(_:)), for: .editingChanged)
myTextField.addTarget(context.coordinator, action: #selector(Coordinator.textFieldDown(_:)), for: .primaryActionTriggered)
myTextField.text = self.Text
myTextField.placeholder = placeHolder
myTextField.borderStyle = border
myTextField.keyboardType = type
myTextField.returnKeyType = .done
myTextField.frame(forAlignmentRect: .zero)
myTextField.setContentHuggingPriority(.defaultHigh, for: .vertical)

return myTextField
}

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

使用方法 1:不带边框

1
2
@State var text = "Hello World"
UIKitTextField(placeHolder: "Placeholder", type: .default, Text: $text).padding()

使用方法 2:带边框

1
2
@State var text = "Hello World"
UIKitTextField(placeHolder: "Placeholder", type: .default, border: .roundedRect, Text: $text).padding()

说明

Type:键盘类型,可参考 https://developer.apple.com/documentation/uikit/uikeyboardtype

Border:外边框,样式可参考 https://developer.apple.com/documentation/uikit/uitextfield/borderstyle

Enjoy it ~

 海报

 评论


字数统计:25.3k  |   正在计算...
总访问量为 次 。