Last active
April 20, 2024 09:58
-
-
Save benigumocom/c3276dd6d0672a03432a50ad75a78c13 to your computer and use it in GitHub Desktop.
【SwiftUI】Search TextField を作る 👉 https://android.benigumo.com/20240415/search-textfield/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct TestSearchTextField: View { | |
@Binding var text: String | |
@FocusState private var focused: Bool | |
var body: some View { | |
VStack { | |
HStack(spacing: 0){ | |
Button { | |
} label: { | |
HStack(alignment: .center, spacing: 0) { | |
Image(systemName: "magnifyingglass") | |
Image(systemName: "chevron.down") | |
.font(.caption) | |
} | |
.padding(8) | |
} | |
.buttonStyle(.borderless) | |
TextField("custom", text: $text) | |
.textFieldStyle(.plain) | |
.focused($focused) | |
Button { | |
text = "" | |
} label: { | |
Image(systemName: "xmark.circle.fill") | |
.padding(8) | |
} | |
.buttonStyle(.borderless) | |
.opacity(text.count > 0 ? 1 : 0) | |
.animation(.default, value: text.count > 0) | |
} | |
.background(.background) | |
.clipShape(.rect(cornerRadius: 8)) | |
.background { | |
RoundedRectangle(cornerRadius: 8) | |
.stroke(.gray, lineWidth: 0.5) | |
RoundedRectangle(cornerRadius: 8) | |
.stroke( | |
focused ? .orange : .clear, | |
lineWidth: focused ? 5 : 16 | |
) | |
} | |
.animation(.default, value: focused) | |
TextField("default", text: .constant("")) | |
.textFieldStyle(.roundedBorder) | |
} | |
.padding() | |
} | |
} | |
#Preview(".constant(\"\")") { | |
TestSearchTextField(text: .constant("")) | |
.frame(width: 300) | |
} | |
#Preview(".constant(\"dog\")") { | |
TestSearchTextField(text: .constant("dog")) | |
.frame(width: 300) | |
} | |
#Preview("return") { | |
@State var text = "dog" | |
return TestSearchTextField(text: $text) | |
.frame(width: 300) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
【SwiftUI】#Preview with @binding arguments
👉 https://android.benigumo.com/20240420/preview-with-binding/
sc.2024-04-20.at.18.33.53.mov