Notice
Recent Posts
Recent Comments
Link
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Archives
Today
Total
관리 메뉴

주니곰의 괴발노트

SwiftUI - Search Bar 구현 본문

iOS

SwiftUI - Search Bar 구현

Jhe2 2023. 5. 11. 21:54

 기본 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
        }
    }
}

서치바 UI

 

 

 빈화면 터치해서 키보드 내리기

#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