这里写自定义目录标题
- 前言/背景
- 实现
- 参考
前言/背景
使用SwiftUI框架,希望在文本框TextField控件中输入内容后显示一个清除按钮,可以清空内容,像这样:
UIKit 框架的 UITextField可以配置clearButtonMode,但是SwiftUI框架里的TextField没有这个,需要自己实现。
IOS开发我不熟悉,也没花时间去细学,本解决方案来自 stackoverflow
建议多使用英文技术网站,这么简单一个问题我在中文网站搜了好久都没找到,要么文不对题要么需要付费(不是说不尊重别人的知识,只是就这么点东西~)
如果stackoverflow打开总是提示人机验证但是又没有可操作的图片或按钮那就是由于某些大家都熟知的原因没加载完全,参考Google 人机验证(reCaptcha)无法显示解决方案
可以解决。
如果英文不会,用关键字即可,例如 [ SwiftUI TextField clear button],这也比百度上啃哧吭哧搜好得多。
实现
- 新建一个swiftUI文件,创建一个clearButton组件,注意实现ViewModifier协议;以及使用ZStack来将按钮放在框内。
struct ClearButton: ViewModifier
{
@Binding var text: String
public func body(content: Content) -> some View
{
ZStack(alignment: .trailing)
{
content
if !text.isEmpty
{
Button(action:
{
self.text = ""
})
{
Image(systemName: "delete.left")
.foregroundColor(Color(UIColor.opaqueSeparator))
}
.padding(.trailing, 8)
}
}
}
}
- 在TextField处添加对clearButton的使用
struct TestView : View {
@Binding var label: String
var body: some View {
VStack {
TextField("951405", text: $label)
.textFieldStyle(.roundedBorder) // 圆角边框
.modifier(TextFieldClearButton(text: $label)) //使用clearbutton
}
}
}
参考
[1] https://stackoverflow.com/questions/58200555/swiftui-add-clearbutton-to-textfield
[2] https://sanzaru84.medium.com/swiftui-how-to-add-a-clear-button-to-a-textfield-9323c48ba61c