2016-07-21 43 views
3

テーブルビューをinputviewとして表すテキストフィールドがあります。私はこのテーブルビューに2つのものを追加したい。すぐにテーブルビューにプログラムで検索バーを追加する

1)検索バーを追加します。
2)キャンセルボタンをテーブルビューの上部に追加します。

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/Introduction/Intro.html) これは実装に役立ちます。 – Chandan

+0

私は客観的なCを知っていれば助けてくれるはずです。私はコードを調べ続けるつもりです。 –

答えて

1

ここでは同じコードスニペットを使用しています。詳しくは、コメントに記載されているApple Docを参照してください。 ///テーブルビュー

UISearchDisplayControllerがIOS8.0で非推奨とContactTVCこれはあなたが

をたくさん助ける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) 
} 
関連する問題