Issues setting up searchdisplaycontroller with tableview - Swift - ios

I'm trying to setup the searchdisplaycontroller up for my tableview and am experiencing a couple of issues when declaring my iboutlet for the tableview itself. Attached is a screenshot as well as my code. Any insight much appreciated.
Code Errors Img
import UIKit
class DataTableExercisesTableViewController: UITableViewController, UISearchBarDelegate {
var exercises = ["Abs", "Arms", "Back", "Chest", "Legs", "Shoulders", "Triceps"]
var searchActive : Bool = false
#IBOutlet var tableView: UITableView!
#IBOutlet weak var searchBar: UISearchBar!
var filtered:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
tableView.delegate = self
tableView.dataSource = self
searchBar.delegate = self
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(searchActive) {
return filtered.count
}
return exercises.count;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell;
if(searchActive){
cell.textLabel?.text = filtered[indexPath.row]
} else {
cell.textLabel?.text = exercises[indexPath.row];
}
return cell;
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchActive = true;
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchActive = false;
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchActive = false;
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchActive = false;
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
filtered = exercises.filter({ (text) -> Bool in
let tmp: NSString = text
let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
return range.location != NSNotFound
})
if(filtered.count == 0){
searchActive = false;
} else {
searchActive = true;
}
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

Have you tried removing the IBoutlet completely? (Both from storyboard connections and in your code). I think this will solve your issue.

Related

Add a Searchbar on TableView but no response

Referring to shrikar's work - ://shrikar.com/swift-ios-tutorial-uisearchbar-and-uisearchbardelegate/, I try to build a searchbar in table view. The tableview works fine when no adding search text. The problem is no response and error message when add search text.
I wonder something wrong. Could anybody help us? Thanks.
import UIKit
import SDWebImage
class ArticleListViewController: UITableViewController, UISearchBarDelegate{
#IBOutlet weak var searchBar: UISearchBar!
var searchActive : Bool = false
var filtered = [Article]()
var articles = [Article](){
didSet{
DispatchQueue.main.async{
self.tableView.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
downLoadLatestArticles()
}
func downLoadLatestArticles(){
Article.downLoadItem { (articles, error) in
if let error = error {
print("fail \(error)")
return
}
if let articles = articles {
self.articles = articles
}
}
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchActive = true;
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchActive = false;
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchActive = false;
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchActive = false;
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if(searchText == " "){
searchActive = false
}else{
filtered = articles.filter ({ (article_f) -> Bool in
let tmp: String = article_f.name
let range = tmp.range(of:searchText, options: String.CompareOptions.caseInsensitive)
return range != nil
})
if(filtered.count == 0){
searchActive = false;
} else {
searchActive = true;
}
}
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(searchActive) {
return filtered.count
}
return articles.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ListTableCell", for: indexPath) as! ListTableCell
var article : Article
if(searchActive){
article = filtered[indexPath.row]
}
else{
article = articles[indexPath.row]
}
cell.nameLabel?.text = article.name
cell.locationLabel?.text = article.location
cell.photoView?.sd_setImage(with: article.image_URL)
return cell
}
}

Search Bar is not filtering properly

I have a search bar in my tableview, but when I initially click on the search bar, the results disappear. If I segue to another controller, and come back, the search bar works fine, with all the results showing when the bar is clicked.
Here is the code:
#IBOutlet weak var toolTable: UITableView!
#IBOutlet weak var searchForTool: UISearchBar!
var searchActive : Bool = false
{
didSet {
if searchActive != oldValue {
toolTable?.reloadData()
}
}
}
typealias Item = (data: String, identity: String)
var filtered: [Item] = []
var items: [Item] = [
(data: " Data1", identity: "A"),
(data: " Data2", identity: "B")
]
override func viewDidLoad() {
super.viewDidLoad()
toolTable.delegate = self
toolTable.dataSource = self
searchForTool.delegate = self
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchActive = true
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchActive = false
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchActive = false
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchActive = false
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filtered = items.filter { item in
item.data.localizedCaseInsensitiveContains(searchText)
}
searchActive = !filtered.isEmpty
self.toolTable.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(searchActive) {
return filtered.count
}
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell
if(searchActive){
cell.toolLabel.text = filtered[indexPath.row].data
} else {
cell.toolLabel.text = items[indexPath.row].data
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vcName: String
if searchActive {
vcName = filtered[indexPath.row].identity
} else {
vcName = items[indexPath.row].identity
}
let viewController = storyboard?.instantiateViewController(withIdentifier: vcName)
self.navigationController?.pushViewController(viewController!, animated: true)
}
I'm sure its some simple solution, I'm just overlooking it.
Any help would be greatly appreciated.
Reading your code I see that: searchBarTextDidBeginEditing sets searchActive to true. The data will be reloaded as per the code in didSet. tableView:numberOfRowsInSection is then called and filtered.count is returned, meaning 0 as it's empty. That's why results disappear.

search bar in ios swift

I want to use search bar in my app.I am trying to use it but exceptions are coming . I have got an array of dictionary called member [[String:Anyobject]] and from this i have taken out the name and stored into an array data of type string and it is not working.
Here is my code :
import UIKit
class hcbaViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate {
#IBOutlet var searchbar: UISearchBar!
#IBOutlet var tableview: UITableView!
var member = [[String:AnyObject]]()
var members = [String:AnyObject]()
var searchActive = true
var filtered:[String] = []
var data: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
print(data)
print("________-----------________----------")
print(member)
// Do any additional setup after loading the view.
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchActive = true
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchActive = false
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchActive = false
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchActive = false
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filtered = data.filter({ (text) -> Bool in
let tmp:NSString = text as NSString
let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
return range.location != NSNotFound
})
if (filtered.count == 0){
searchActive = false
}
else{
searchActive = true
}
self.tableview.reloadData()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "MemberDirectory"
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return member.count
if(searchActive){
return filtered.count
}
else{
return data.count
}
// return member.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath)
var display = member[indexPath.row]
cell.textLabel?.text = display["Name"] as! String?
cell.detailTextLabel?.text = display["email"] as? String
let n = display["Name"] as! String
data.append(n)
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! hcbadetailViewController
vc.kk = members
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
members = member[indexPath.row]
self.performSegue(withIdentifier: "bye", sender: nil)
}
You can try this...
class SearchNew: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, GADInterstitialDelegate{
var SearchBarValue:String!
var searchActive : Bool = false
var data : NSMutableArray!
var filtered:NSMutableArray!
#IBOutlet var searchBar: UISearchBar!
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.showsCancelButton = false
tableView.tableFooterView = UIView(frame: CGRectZero)
/* Setup delegates */
tableView.delegate = self
tableView.dataSource = self
searchBar.delegate = self
self.searchBar.delegate = self
data = []
filtered = []
self.getData()
} //-----viewDidLoad closed------
func getData()
{
//insert member data within data array
data.addObject(member)
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchActive = true
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchActive = false
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchActive = false;
searchBar.text = nil
searchBar.resignFirstResponder()
tableView.resignFirstResponder()
self.searchBar.showsCancelButton = false
tableView.reloadData()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchActive = false
}
func searchBarShouldEndEditing(searchBar: UISearchBar) -> Bool {
return true
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
self.searchActive = true;
self.searchBar.showsCancelButton = true
filtered.removeAllObjects()
dispatch_to_background_queue
{
for xdata in self.data
{
let nameRange: NSRange = xdata.rangeOfString(searchText, options: [NSStringCompareOptions.CaseInsensitiveSearch ,NSStringCompareOptions.AnchoredSearch ])
if nameRange.location != NSNotFound{
self.filtered.addObject(xdata)
}
}//end of for
self.dispatch_to_main_queue {
/* some code to be executed on the main queue */
self.tableView.reloadData()
} //end of dispatch
}
}
func dispatch_to_main_queue(block: dispatch_block_t?) {
dispatch_async(dispatch_get_main_queue(), block!)
}
func dispatch_to_background_queue(block: dispatch_block_t?) {
let q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(q, block!)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(searchActive) {
return filtered.count
}else{
return data.count
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "showDetailView") {
if let destination=segue.destinationViewController as? DetailViewController{
let path=tableView.indexPathForSelectedRow
let cell=tableView.cellForRowAtIndexPath(path!)
destination.passedValue=(cell?.textLabel?.text)
}
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
searchBar.resignFirstResponder()
searchBar.endEditing(true)
self.view.endEditing(true)
self.searchBar.showsCancelButton = false
self.searchBar.text=""
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell;
if(searchActive){
cell.textLabel?.text = filtered[indexPath.row] as! NSString as String
} else {
cell.textLabel?.text = data[indexPath.row]as! NSString as String
}
return cell;
}
}
Hope it helps you.
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate {
#IBOutlet var tblview: UITableView!
#IBOutlet var searchview: UISearchBar!
var data:[String] = ["Dev","Hiren","Bhagyashree","Himanshu","Manisha","Trupti","Prashant","Kishor","Jignesh","Rushi"]
var filterdata:[String]!
override func viewDidLoad() {
super.viewDidLoad()
tblview.dataSource = self
searchview.delegate = self
filterdata = data
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filterdata.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tblview.dequeueReusableCell(withIdentifier: "cell", for: indexPath)as!TableViewCell1
if filterdata.count != 0
{
cell.textview.text = filterdata[indexPath.row]
}
else{
cell.textview.text = data[indexPath.row]
}
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
// filterdata = searchText.isEmpty ? data : data.filter {(item : String) -> Bool in
filterdata = searchText.isEmpty ? data : data.filter { $0.contains(searchText) }
//return item.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil
tblview.reloadData()
}
let searchController = UISearchController(searchResultsController: nil)
navigationItem.hidesSearchBarWhenScrolling = true
navigationItem.searchController = searchController
Replace this method with your TableView's method
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(searchActive){
return filtered.count
}
else{
return data.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath)
var display = searchActive == true ? filtered[indexPath.row] :
data[indexPath.row]
cell.textLabel?.text = display["Name"] as! String?
cell.detailTextLabel?.text = display["email"] as? String
let n = display["Name"] as! String
data.append(n)
return cell
}

Error in SearchBar while trying to write some thing using swift3

I'am trying to make a search bar in my table view but I have an error while trying to write any thing in the search bar , The error is (Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier cell1 - must register a nib or a class for the identifier or connect a prototype cell in a storyboard') , I,am making a class to my cell and use it identifier as (cell1) but still the same error , can any one help me to solve this problem using Swift 3 .
This is My Code :
import UIKit
class ProgrTable: UIViewController , UITableViewDataSource , UITableViewDelegate , UISearchBarDelegate {
#IBOutlet weak var ProgTable: UITableView!
#IBOutlet weak var searchBar: UISearchBar!
var searchActive : Bool = false
var filtered:[String] = []
var ProgArray = [UIImage]()
var ProgTitle = [String]()
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
ProgTable.dataSource = self
ProgTable.delegate = self
ProgArray = [UIImage(named :"1")!,UIImage(named :"1")!,UIImage(named :"1")!,UIImage(named :"1")!,UIImage(named :"1")!,UIImage(named :"1")!,UIImage(named :"1")!,UIImage(named :"1")!]
ProgTitle = ["ssss ","kkkkkkk","vvvvvvv","yyyyyy","uuuuuu","eeeee","rrrrr","hhhhh","ggggg","fffff","dddd"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchActive = true;
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchActive = false;
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchActive = false;
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchActive = false;
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filtered = ProgTitle.filter({ (text) -> Bool in
let tmp: NSString = text as NSString
let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
return range.location != NSNotFound
})
if(filtered.count == 0){
searchActive = false;
} else {
searchActive = true;
}
self.ProgTable.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if(searchActive) {
return filtered.count
}
return ProgArray.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1" , for: indexPath ) as! ProgrCell
if(searchActive){
cell.progLable.text = filtered[indexPath.row]
} else {
cell.progLable.text = ProgTitle[indexPath.row]
cell.progImage.image = ProgArray[indexPath.row]
}
return cell
}
}
This is My cell code :
import UIKit
class ProgrCell: UITableViewCell {
#IBOutlet weak var progLable: UILabel!
#IBOutlet weak var progImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
In StoryBoard, select the cell, and make sure that the identifier is cell1, and that the class has been set to 'ProgrCell'

selecting cell in tableview while UISearchController is active, doesnt present next view?

I have made a tableview where you can select a cell, and then the viewcontroller will perform a segue to the next view, which works perfectly fine when you are not using the searchcontroller.
Then when you are using the searchcontroller, it filters the tableview as it should, and the segue is called in didSelectRowAtIndexPath, and the prepareForSegue is called. The problem then is that the view it should segue to is not presented? I can see that the code in the class connected to the view is running, so the segue is performed, it is just the view that does not follow. What am i missing
class CompanyListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating {
#IBOutlet weak var tableView: UITableView!
let objectMapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()
var activityIndicatorView: SWActivityIndicatorView!
var resultSearchController: UISearchController!
var allCompanies: [Company] = []
var filteredCompanies = [Company]()
override func viewDidLoad() {
super.viewDidLoad()
// set delegates
tableView.delegate = self
tableView.dataSource = self
configureSearchController()
// initialize activity indicator view
self.activityIndicatorView = SWActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
activityIndicatorView.hidesWhenStopped = true
activityIndicatorView.color = UIColor.lightGrayColor()
self.view.addSubview(activityIndicatorView)
self.activityIndicatorView.center = self.view.center
activityIndicatorView.startAnimating()
// fetch all records from backend
fetchAllRecords({(errors: [NSError]?) -> Void in if errors != nil {print(errors)}})
}
func configureSearchController() {
// Initialize and perform a minimum configuration to the search controller.
// Search Bar
self.resultSearchController = UISearchController(searchResultsController: nil)
self.resultSearchController?.searchBar.autocapitalizationType = .None
self.tableView.tableHeaderView = self.resultSearchController?.searchBar
resultSearchController?.dimsBackgroundDuringPresentation = false
self.resultSearchController?.searchResultsUpdater = self
definesPresentationContext = true
}
// search delegate method
func updateSearchResultsForSearchController(searchController: UISearchController) {
self.filterContentForSearchText(searchController.searchBar.text!)
}
// Filter method, which filters by companyName, and reloads tableview
func filterContentForSearchText(searchText: String, scope: String = "All") {
filteredCompanies = allCompanies.filter { company in
return company._companyName!.lowercaseString.containsString(searchText.lowercaseString)
}
tableView.reloadData()
}
// fetch all records from backend
func fetchAllRecords(completionHandler: (errors: [NSError]?) -> Void) {
let scanExpression = AWSDynamoDBScanExpression()
objectMapper.scan(Company.self, expression: scanExpression) { (response: AWSDynamoDBPaginatedOutput?, error: NSError?) in
dispatch_async(dispatch_get_main_queue(), {
// if error
if let error = error {
completionHandler(errors: [error]);
}
//if success
else {
self.allCompanies = response!.items as! [Company]
self.tableView.reloadData()
self.activityIndicatorView.stopAnimating()
}
})
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if resultSearchController.active && resultSearchController.searchBar.text != "" {
return filteredCompanies.count
}
return allCompanies.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell:CompanyListTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("companyCell") as! CompanyListTableViewCell
// set the text from the data model
let company:Company?
if resultSearchController.active && resultSearchController.searchBar.text != "" {
company = self.filteredCompanies[indexPath.row]
} else {
company = self.allCompanies[indexPath.row]
}
cell.titleLabel.text = company!._companyName
cell.imageview?.image = UIImage(named: "placeholder")
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("segueToProfile", sender: self)
}
// send selected company with segue to profile
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "segueToProfile"){
let indexPath = tableView.indexPathForSelectedRow
//tableView.deselectRowAtIndexPath(indexPath!, animated: true)
let selectedRow = indexPath!.row
let profileVC = segue.destinationViewController as! ProfileViewController
if resultSearchController.active{
print(filteredCompanies[selectedRow])
profileVC.company = filteredCompanies[selectedRow]
} else {
profileVC.company = allCompanies[selectedRow]
}
}
}
}
The console is saying this, but i dont know if that has anything to do with this?
2016-11-26 15:54:07.300 Lostandfound[949:2474251] Warning: Attempt to present on which is already presenting
Here is the example of TableView with SearchBar control.You should remove didSelectRowAtIndexPath method and use prepareForSegue method for Determine the selected row in TableView.Like this...
Example:
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate
{
#IBOutlet weak var SerchBar: UISearchBar!
#IBOutlet weak var TableView: UITableView!
var searchActive : Bool = false
var data = ["San Francisco","New York","San Jose","Chicago","Los Angeles","Austin","Seattle"]
var filtered:[String] = []
override func viewDidLoad()
{
super.viewDidLoad()
}
private func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if(searchActive)
{
return filtered.count
}
return data.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = self.TableView.dequeueReusableCell(withIdentifier: "Cell") as! TableViewCell
if(searchActive)
{
cell.Label.text = filtered[indexPath.row]
}
else
{
cell.Label.text = data[indexPath.row]
}
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any!)
{
if let cell = sender as? TableViewCell
{
let i = TableView.indexPath(for: cell)!.row
if segue.identifier == "segue1"
{
if(searchActive)
{
let name1 = segue.destination as! SecondView
name1.str = self.filtered[i]
}
else
{
let name1 = segue.destination as! SecondView
name1.str = self.data[i]
}
}
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
{
filtered = data.filter({ (text) -> Bool in
let tmp: NSString = text as NSString
let range = tmp.range(of: searchText, options: .caseInsensitive)
return range.location != NSNotFound
})
if(filtered.count == 0)
{
searchActive = false;
}
else
{
searchActive = true;
}
self.TableView.reloadData()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar)
{
searchActive = true;
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar)
{
searchActive = false;
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar)
{
searchActive = false;
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
{
searchActive = false;
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
}
Your SecondView class is:
import UIKit
class SecondView: UIViewController
{
#IBOutlet weak var label: UILabel!
var str:String!
override func viewDidLoad()
{
super.viewDidLoad()
self.label.text = str
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
}
And your TableViewCell is:
import UIKit
class TableViewCell: UITableViewCell
{
#IBOutlet weak var Label: UILabel!
override func awakeFromNib()
{
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
}
}

Resources