A specialized view for receiving search-related information from the user.
@MainActor class UISearchBar : [UIView](<https://developer.apple.com/documentation/uikit/uiview>)
UISearchBar
provides a text field for entering text, a search button, a bookmark button, and a cancel button. A search bar doesn’t actually perform any searches. You use a delegate, an object conforming to the UISearchBarDelegate
protocol, to implement the actions when the user enters text or clicks buttons. For details about interacting with the text field, accessing its content, and using tokens, see UISearchTextField
and UISearchToken
.
UISearchBar
은 텍스트 입력용 텍스트 필드, 검색 단추, 책갈피 단추 및 취소 단추를 제공합니다. 검색 표시줄은 실제로 검색을 수행하지 않습니다. 사용자가 텍스트를 입력하거나 단추를 클릭할 때 작업을 구현하려면 UISearchBarDelegate
프로토콜을 준수하는 개체인 delegate
를 사용합니다. 텍스트 필드와의 상호 작용, 내용 접근 및 토큰 사용에 대한 자세한 내용은 UISearchTextField
및 UISearchToken
을 참조하십시오.You can customize the appearance of search bars one at a time, or you can use the appearance proxy ([UISearchBar appearance]
) to customize the appearance of all search bars in an app.
In general, you should specify a value for the normal state to be used by other states which don’t have a custom value set. Similarly, when a property is dependent on the bar metrics (on iPhone, in landscape orientation bars have a different height from standard), you should specify a value for UIBarMetricsDefault
.
UISearchBar appearance
")를 사용하여 앱에 있는 모든 검색 줄의 모양을 사용자 정의할 수 있습니다.일반적으로 사용자 정의 값이 설정되지 않은 다른 상태에서 사용할 정상 상태의 값을 지정해야 합니다. 마찬가지로 속성이 막대 메트릭에 종속된 경우(iPhone에서 가로 방향 막대의 높이가 표준과 다른 경우), 'UIBarMetricsDefault
'에 대한 값을 지정해야 합니다.
import UIKit
final class DiaryListViewController: UIViewController {
typealias DataSource = UITableViewDiffableDataSource<Section, DiaryContent>
typealias Snapshot = NSDiffableDataSourceSnapshot<Section, DiaryContent>
enum Section {
case main
}
private lazy var dataSource = self.configureDataSource()
private var diaryListViewModel = DiaryViewModel()
private var fileteredData = [DiaryContent]()
private var searchController: UISearchController = {
let searchController = UISearchController(searchResultsController: nil)
return searchController
}()
private let diaryListTableView: UITableView = {
let tableView = UITableView()
tableView.register(DiaryTableViewCell.self, forCellReuseIdentifier: DiaryTableViewCell.identifier)
tableView.translatesAutoresizingMaskIntoConstraints = false
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupDefault()
configureLayout()
updateDataSource(data: diaryListViewModel.diaryContents)
registerNotificationForTableView()
}
private func setupDefault() {
self.view.backgroundColor = .white
self.diaryListTableView.delegate = self
diaryListTableView.tableHeaderView = self.searchController.searchBar
self.definesPresentationContext = true
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.delegate = self
}
private func configureDataSource() -> DataSource {
dataSource = DataSource(tableView: diaryListTableView, cellProvider: { tableView, indexPath, content -> UITableViewCell? in
guard let cell = tableView.dequeueReusableCell(withIdentifier: DiaryTableViewCell.identifier, for: indexPath) as? DiaryTableViewCell else {
return UITableViewCell()
}
cell.configureUI(data: content)
cell.accessoryType = .disclosureIndicator
return cell
})
return dataSource
}
private func updateDataSource(data: [DiaryContent]) {
var snapshot = Snapshot()
snapshot.appendSections([.main])
snapshot.appendItems(data)
dataSource.apply(snapshot, animatingDifferences: false, completion: nil)
}
private func configureLayout() {
self.view.addSubview(diaryListTableView)
NSLayoutConstraint.activate([
diaryListTableView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
diaryListTableView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
diaryListTableView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),
diaryListTableView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)
])
}
}
extension DiaryListViewController: UISearchBarDelegate, UISearchResultsUpdating, UISearchControllerDelegate {
func updateSearchResults(for searchController: UISearchController) {
let filter = diaryListViewModel.diaryContents.filter({ (data: DiaryContent) -> Bool in
return data.title.uppercased().contains((searchController.searchBar.text?.uppercased())!)
})
fileteredData = filter.isEmpty ? diaryListViewModel.diaryContents : filter
self.updateDataSource(data: fileteredData)
diaryListTableView.reloadData()
}
}