不需要第三方解决方案
可以通过以下方法来增加可点击区域,而无需使用第三方工具:
步骤1:创建一个修改过的TextField
。这样做是为了定义我们新的TextField
的填充:
代码取自 - https://dev59.com/t18e5IYBdhLWcg3wyM0r#27066764
class ModifiedTextField: UITextField {
let padding = UIEdgeInsets(top: 20, left: 5, bottom: 0, right: 5)
override open func textRect(forBounds bounds: CGRect) -> CGRect {
bounds.inset(by: padding)
}
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
bounds.inset(by: padding)
}
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
bounds.inset(by: padding)
}
}
步骤2:将新的ModifiedTexField
转换为UIViewRepresentable
,以便我们可以在SwiftUI
中使用它:
struct EnhancedTextField: UIViewRepresentable {
@Binding var text: String
init(text: Binding<String>) {
self._text = text
}
func makeUIView(context: Context) -> ModifiedTextField {
let textField = ModifiedTextField(frame: .zero)
textField.delegate = context.coordinator
return textField
}
func updateUIView(_ uiView: ModifiedTextField, context: Context) {
uiView.text = text
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UITextFieldDelegate {
let parent: EnhancedTextField
init(_ parent: EnhancedTextField) {
self.parent = parent
}
func textFieldDidChangeSelection(_ textField: UITextField) {
parent.text = textField.text ?? ""
}
}
}
步骤3:在需要的地方使用新的EnhancedTextField
:
EnhancedTextField(placeholder: placeholder, text: $binding)
注意:要增加或减少可点击区域,只需在ModifiedTextField
中更改填充即可。
let padding = UIEdgeInsets(top: 20, left: 5, bottom: 0, right: 5)
UIViewRepresentable
来表示UITextField之外,仍然没有解决方案。 - Daniel