2016-07-21 3 views
3

tableview를 inputview로 나타내는 텍스트 필드가 있습니다. 이 테이블 뷰에 2 가지를 추가하고 싶습니다.신속하게 테이블 뷰에 검색 막대 추가 프로그래밍 방식으로 검색 막대 추가

1) 검색 창을 추가하십시오.
2) 취소 버튼을 tableview 상단에 추가하십시오.

class enterYourDealVC: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate, UISearchResultsUpdating { 
var tableView: UITableView = UITableView() 
let searchController = UISearchController(searchResultsController: nil) 

var dealAirports = [ 
    airPorts(name: "Airport1", shortcut: "AP1")!), 
    airPorts(name: "Airport2", shortcut: "AP2")!) 
] 
var filteredAirports = [airPorts]() 


//view did load 
    tableView = UITableView(frame: UIScreen.mainScreen().bounds, style: UITableViewStyle.Plain) 
    tableView.delegate  = self 
    tableView.dataSource = self 
    tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") 

    searchController.searchResultsUpdater = self 
    searchController.dimsBackgroundDuringPresentation = false 
    definesPresentationContext = true 
    tableView.tableHeaderView = searchController.searchBar 
    toTextField.inputView = self.tableView 

//here is my search function 
func filterContentForSearchText(searchText: String, scope: String = "All") { 
    filteredAirports = dealAirports.filter { ap in 
     return ap.name.lowercaseString.containsString(searchText.lowercaseString) 
    } 

    tableView.reloadData() 
} 
} 

문제는이 코드와 함께 검색하지 않습니다. 또한 검색 막대를 클릭하면 tableview가 닫히고 다시 viewcontroller로 돌아옵니다. 이 문제를 어떻게 해결할 수 있습니까?

및이 테이블 뷰에 취소 버튼을 어떻게 추가합니까?

+0

UISearchController Apple 샘플 코드 : [Apple sample code] (https://developer.apple.com/libr) ary/ios/samplecode/TableSearch_UISearchController/소개/Intro.html) 구현하는 데 도움이됩니다. – Chandan

+0

내가 객관적인 C를 알면 나에게 도움이 될 수있다. 나는 매우 복잡해 보인다. 코드를 계속 검토 할 것입니다. –

답변

1

여기에 같은 코드 스 니펫이 있습니다. 자세한 내용은 주석에 언급 된 Apple 문서를 참조하십시오. /// 테이블보기

UISearchDisplayController는 IOS8.0에서 사용되지 않는, 그리고 ContactTVC이 당신이

을 alot을 도움이 될 것입니다 UISearchController

희망을 사용하는 것이 좋습니다

class ContactTVC:UITableViewController{ 
// MARK: Types 
/// State restoration values. 
enum RestorationKeys : String { 
    case viewControllerTitle 
    case searchControllerIsActive 
    case searchBarText 
    case searchBarIsFirstResponder 
} 

struct SearchControllerRestorableState { 
    var wasActive = false 
    var wasFirstResponder = false 
} 


/* 
The following 2 properties are set in viewDidLoad(), 
They an implicitly unwrapped optional because they are used in many other places throughout this view controller 
*/ 

/// Search controller to help us with filtering. 
var searchController: UISearchController! 

/// Secondary search results table view. 
var resultsTableController: ResultsTableController! 

/// Restoration state for UISearchController 
var restoredState = SearchControllerRestorableState() 
var arrayContacts: Array<CNContact> = [] 
var searchResultArrayContacts: Array<CNContact> = [] 

override func viewDidLoad() { 
    super.viewDidLoad() 

    resultsTableController = ResultsTableController() 
// We want to be the delegate for our filtered table so didSelectRowAtIndexPath(_:) is called for both tables. 
    resultsTableController.tableView.delegate = self 

    searchController = UISearchController(searchResultsController: resultsTableController) 

    searchController.searchResultsUpdater = self 
    searchController.searchBar.sizeToFit() 
    tableView.tableHeaderView = searchController.searchBar 

    searchController.delegate = self 
    searchController.dimsBackgroundDuringPresentation = false // default is YES 
    searchController.searchBar.delegate = self // so we can monitor text changes + others 

    /* 
    Search is now just presenting a view controller. As such, normal view controller 
    presentation semantics apply. Namely that presentation will walk up the view controller 
    hierarchy until it finds the root view controller or one that defines a presentation context. 
    */ 

    definesPresentationContext = true 

} 

override func viewDidAppear(animated: Bool) { 
    super.viewDidAppear(animated) 

    // Restore the searchController's active state. 
    if restoredState.wasActive { 
     searchController.active = restoredState.wasActive 
     restoredState.wasActive = false 

     if restoredState.wasFirstResponder { 
      searchController.searchBar.becomeFirstResponder() 
      restoredState.wasFirstResponder = false 
     } 
    } 
} 

//MARK override TableViewDelegates/Datasource methods 
} 
extension ContactTVC: UISearchResultsUpdating{ 

// MARK: UISearchResultsUpdating 

func updateSearchResultsForSearchController(searchController: UISearchController) { 

     if let text = searchController.searchBar.text where (text.isEmpty == false){ 
     { 

          // Hand over the filtered results to our search results table. 

          let resultsController = searchController.searchResultsController as! ResultsTableController 

          resultsController.filteredProducts = Array(searchResult) 

          resultsController.tableView.reloadData() 

         dispatch_async(dispatch_get_main_queue(), { 
          self.tableViewContacts.reloadData() 
         }) 

       } 
     } 
} 
} 
//MARK: SearchBarDelegate 
extension ContactTVC: UISearchBarDelegate{ 

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { 

    if let text = searchBar.text where (text.isEmpty == false) { 

      // update the search result array by filtering…. 


       if searchResult.count > 0{ 

        self.searchResultArrayContacts = Array(searchResult) 
       } 
       else{ 

        self.searchResultArrayContacts = Array(self.arrayContacts) 
       } 

       dispatch_async(dispatch_get_main_queue(), { 
        self.tableViewContacts.reloadData() 
       }) 
    } 
} 


func searchBarCancelButtonClicked(searchBar: UISearchBar) { 

    searchBar.text = nil 
    searchBar.resignFirstResponder() 

} 
} 

사용자가 검색 필드에 입력 한대로 필터링 된 제품을 표시하는 컨트롤러.

class ResultsTableController: UITableViewController { 
// MARK: Properties 

let reusableIdentifier = "contactCell" 

var filteredProducts = [CNContact]() 

override func viewDidLoad() { 

    self.tableView.emptyDataSetSource = self 
    self.tableView.emptyDataSetDelegate = self 

} 


// MARK: UITableViewDataSource 
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    return filteredProducts.count 
} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: reusableIdentifier) 

    var contact = CNContact() 
    contact = filteredProducts[indexPath.row] 

    // Configure the cell... 
    cell.textLabel?.text = contact.givenName 

    let phones = contact.phoneNumbers[0].value as! CNPhoneNumber 

    cell.detailTextLabel?.text = phones.stringValue 

    return cell 
} 
} 

감사

4

이것은 SeachBar을 추가합니다

lazy var searchBar:UISearchBar = UISearchBar() 

override func viewDidLoad() 
{ 
    searchBar.searchBarStyle = UISearchBarStyle.Prominent 
    searchBar.placeholder = " Search..." 
    searchBar.sizeToFit() 
    searchBar.translucent = false 
    searchBar.backgroundImage = UIImage() 
    searchBar.delegate = self 
    navigationItem.titleView = searchBar 

} 

func searchBar(searchBar: UISearchBar, textDidChange textSearched: String) 
{ 
    ...your code... 
} 
1

// 검색을위한 첫번째 쓰기 위임 "UISearchBarDelegate" // MARK : - 검색 버튼 액션

@IBAction func searchWithAddress(_ sender: Any) { 
let searchController = UISearchController(searchResultsController: nil) 
searchController.searchBar.delegate = self 
self.present(searchController, animated: true, completion: nil) 
} 
관련 문제