주니곰의 괴발노트
SwiftUI - Search Bar 구현 본문
기본 UI 구현
import SwiftUI
struct SearchBar: View {
@State private var text: String = ""
@State private var isEditing: Bool = false
var body: some View {
ZStack {
Rectangle()
.foregroundColor(Color.init(uiColor: .systemBackground))
.ignoresSafeArea()
VStack {
HStack {
Image(systemName: "magnifyingglass")
.foregroundColor(.gray)
.padding(.leading, 16)
TextField("Place Holder...", text: $text)
.onTapGesture { isEditing = true }
if isEditing {
Button {
text = ""
} label: {
Image(systemName: "multiply.circle.fill")
.foregroundColor(.gray)
.padding(.trailing, 16)
}
.buttonStyle(.plain)
}
}
.padding(.bottom, 8)
Rectangle()
.foregroundColor(.black)
.frame(height: 2)
.padding(.horizontal, 16)
}
}
.onTapGesture {
hideKeyboard()
isEditing = false
}
}
}
빈화면 터치해서 키보드 내리기
#if canImport(UIKit)
extension View {
func hideKeyboard() {
UIApplication
.shared
.sendAction(
#selector(UIResponder.resignFirstResponder),
to: nil,
from: nil,
for: nil
)
}
}
#endif
참고
https://www.appcoda.com/swiftui-search-bar/
'iOS' 카테고리의 다른 글
Swift - Generic (0) | 2023.06.02 |
---|---|
Swift - Concurrency (0) | 2023.05.13 |
Swift - 열거형 (0) | 2023.03.12 |
Swift - Extensions (0) | 2023.03.05 |
Swift - Concurrency (동시성) (0) | 2023.02.26 |
Comments