Notice
Recent Posts
Recent Comments
Link
«   2025/08   »
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
31
Tags
more
Archives
Today
Total
관리 메뉴

Olive Study Room

[iOS] UISearchBar - 검색기능 구현하기 (1) 필수항목 본문

Coding/iOS

[iOS] UISearchBar - 검색기능 구현하기 (1) 필수항목

Olive Dev 2021. 4. 30. 15:25

var searchBar: UISearchBar { get }

interface에 설치하기 위한 search bar

 

검색가능한 콘텐츠를 보여주기 이전에,  view 계층 어딘가에 search bar를 설치한다. search bar는 콘텐츠를 검색하는 시작점이다. search bar와의 상호작용은 (검색정보가 변경될 때마다 searchResultsUpdater 속성의 개체에 알리는) UISearch Controller 객체에 의해 자동적으로 작동된다.

 

UISearch Controller를 서브 클래스로 지정하고 커스텀 실행을 되돌리기 위한 이 프로퍼티를 오버라이딩함으로써 custom search bar를 제공할 수 있다. Search bar를 정확한 형태로 보장하기 위해, 아래 코드와 같이, 처음 요청했을 때 lazily하게 초기화한다. (lazy..?)

 

class CustomSearchController: UISearchController {

    // searchBar 프로퍼티가 호출될 때까지 이 속성을 초기화를 연기하는 것이 lazy하다고 표시한다.
    // lazy에 관한 포스팅은 따로 준비 중
    private lazy var customSearchBar = CustomSearchBar()

    // 커스텀 실행을 리턴하기 위해 이 프로퍼티를 오버라이딩하라.
    override var searchBar: UISearchBar { customSearchBar }
}

대량의 항목 목록을 스크롤하는 것은 사용자에게 느리고 실망스러운 과정이 될 수 있다. 대규모 데이터를 다를 때, 사용자가 특정 아이템을 검색하도록 하는 것이 매우 중요하다. UIKit은 UISearchController에 의해 UINavigationItem와 통합하고, 정보를 빠르고 반응성있게 필터링하도록 하는 UISearchBar를 포함한다.

 


1. Search Bar 띄우기 & 세팅

 

  • 변수 선언
// search Controller 생성
let searchController = UISearchController(searchResultsController: nil)

// 나중에 result를 update시키기 위함
var isSearchBarEmpty: Bool {
  return searchController.searchBar.text?.isEmpty ?? true
}
var isfiltering: Bool {
  return searchController.isActive && !isSearchBarEmpty
}
  • 띄우기 및 설정
// iOS 11에서는 네비게이션 아이템에 search bar를 넣는 것이 필수. --> 필수
// 아직 인터페이스 빌더가 search bar와 호환되지 않기 때문이다.
navigationItem.searchController = searchController

// search bar내의 텍스트 변경사항을 클래스에 알려준다.  --> 필수
searchController.searchResultsUpdater = self


// 검색 중인 정보가 들어있는 뷰 컨트롤러를 흐리게한다. 
searchController.obscuresBackgroundDuringPresentation = false
// 안내 메시지를 띄운다.
searchController.searchBar.placeholder = "Search Candies"

// 다른 뷰 컨트롤러로 넘어갈 경우 search bar가 남아있지 않게 한다.
definesPresentationContext = true

 

 

2. UISearchResultsUpdating과 필터링

  • 변수 선언
// 검색한 결과를 띄워주기 위한 배열
var filteredCandies: [Candy] = []
var isSearchBarEmpty: Bool {
  return searchController.searchBar.text?.isEmpty ?? true
}

 

  • 필터링 후 텍스트 바뀔 때마다 reloadData()
func filterContentForSearchText(_ searchText: String,
                                category: Candy.Category? = nil) {
  filteredCandies = candies.filter { (candy: Candy) -> Bool in
    return candy.name.lowercased().contains(searchText.lowercased())
  }
  
  tableView.reloadData()
}
extension MasterViewController: UISearchResultsUpdating {
  func updateSearchResults(for searchController: UISearchController) {
    let searchBar = searchController.searchBar
    filterContentForSearchText(searchBar.text!)
  }
}

 

 

3. 테이블 뷰 업데이트

var isFiltering: Bool {
  return searchController.isActive && !isSearchBarEmpty
}

isFiltering이 true면 filteredCandies의 row로 업데이트

func tableView(_ tableView: UITableView,
               numberOfRowsInSection section: Int) -> Int {
  if isFiltering {
    return filteredCandies.count
  }
    
  return candies.count
}
func tableView(_ tableView: UITableView, 
               cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
  let candy: Candy
  if isFiltering {
    candy = filteredCandies[indexPath.row]
  } else {
    candy = candies[indexPath.row]
  }
  cell.textLabel?.text = candy.name
  cell.detailTextLabel?.text = candy.category.rawValue
  return cell
}

 

 

* navigation Controller를 embed in 시켜줘야 나타남

 

공부 출처 : www.raywenderlich.com/4363809-uisearchcontroller-tutorial-getting-started

'Coding > iOS' 카테고리의 다른 글

[Swift] components(separatedBy:) & split  (0) 2021.06.07
[Swift] RawRepresentable  (0) 2021.05.01
[iOS] Photos Framework (1) 개념  (0) 2021.04.13
[Swift] GCD? (Dispatch Queue & OperationQueue)  (1) 2021.04.06
[Swift] Json 다루기  (0) 2021.03.12
Comments