2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SwiftUIでSearchBarを作ってみた

2
Last updated at Posted at 2021-06-22

はじめに

SwiftUIにSearchBarが無くて困ったので、自作してみました。
paddingやcornerRadius等の値は多少雑になっているので、気になる方は数値を調整してください。

SerachBar

struct SearchBar: View {
    
    @Binding var text: String
    @State private var isEditing = false

    var onSearchButtonClick: () -> Void
    
    var body: some View {
        ZStack(alignment: .leading) {
            HStack {
                
                Image(systemName: "magnifyingglass")
                    .foregroundColor(Color(.lightGray))
                    .padding(.leading, 5)
                
                TextField("Search", text: $text,
                          onCommit: {
                            self.onSearchButtonClick()
                          }
                )
                .padding(.top, 5)
                .padding(.bottom, 5)
                .padding(.leading, -5)
                .onTapGesture {
                    self.isEditing = true
                }
                
                if isEditing {
                    Button(action: {
                        self.text = ""
                    }, label: {
                        Image(systemName: "multiply.circle.fill")
                            .foregroundColor(.gray)
                            .offset(x: -5)
                    })
                }
                
            }
        }
        .background(Color(.systemGray6))
        .cornerRadius(8)
    }
    
    public func onSearchButtonClick(action: () -> Void) -> some View {
        action()
        return self
    }
}

見た目はこれで完成ですが、キーボードのreturnKeyがデフォルトのままなので、変更します。

returnKeyTypeを変更

ライブラリを追加

pod 'Introspect'

他の記事を見ていると、ライブラリなしでもできるみたいですが、自分の環境だと動作しませんでした。

SearchBarを呼び出すViewにて

import SwiftUI
import Introspect

struct SomeView: View {
    @State var searchWord: String = ""
    
    var body: some View {
        SearchBar(text: $searchWord,
                  onSearchButtonClick: {
                    print("Did tap search button")
                  })
            .padding(.leading, 5)
            .padding(.trailing, 5)
            .introspectTextField { textField in
                textField.returnKeyType = .search
            }
    }
}

結果

Simulator Screen Shot - iPod touch (7th generation) - 2021-06-22 at 10.43.41.png

以上です。

2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?