SwiftUI:将 ClearButton 添加到 TextField [英] SwiftUI: Add ClearButton to TextField
本文介绍了SwiftUI:将 ClearButton 添加到 TextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在选择特定的文本字段时在swifui中添加一个clearbutton到swifui中的textfield.
I am trying to add a ClearButton to TextField in SwiftUI when the particular TextField is selected.
我得到的最接近的是创建一个 ClearButton
ViewModifier
并使用 .modifer()
将它添加到 TextField
>
The closest I got was creating a ClearButton
ViewModifier
and adding it to the TextField
using .modifer()
唯一的问题是 ClearButton
是永久性的,并且在取消选择 TextField
时不会消失
The only problem is ClearButton
is permanent and does not disappear when TextField
is deselected
TextField("Some Text" , text: $someBinding).modifier(ClearButton(text: $someBinding))
struct ClearButton: ViewModifier {
@Binding var text: String
public func body(content: Content) -> some View {
HStack {
content
Button(action: {
self.text = ""
}) {
Image(systemName: "multiply.circle.fill")
.foregroundColor(.secondary)
}
}
}
}
推荐答案
使用 ZStack
来定位出现在 TextField
内的清除按钮.
Use ZStack
to position the clear button appear inside the TextField
.
TextField("Some Text" , text: $someBinding).modifier(ClearButton(text: $someBinding))
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)
}
}
}
}
这篇关于SwiftUI:将 ClearButton 添加到 TextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文