Метод DidSelectRow не вызывается

Привет, ребята, я пытался в течение нескольких дней без ответа. Я уже реализовал UITableViewDelegate а также UITableViewDataSource прежде чем поднять этот вопрос мой didSelectRowAt а также didDeselectRowAtОба метода не работают.

class SearchClass: UIViewController, UITableViewDataSource,UITableViewDelegate, UISearchBarDelegate {

@IBOutlet weak var myTableView: UITableView!
@IBOutlet weak var mySearchBar: UISearchBar!

var objects:PFObject!

var searchResults = [String]()

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.navigationController?.navigationBar.topItem?.title = "Search"
    self.navigationController?.navigationBar.barTintColor = UIColor.white
    self.navigationController?.navigationBar.backgroundColor = UIColor.black
    self.navigationController?.navigationBar.tintColor = UIColor.black
    self.searchResults.removeAll()

}


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.myTableView.dataSource = self
    self.mySearchBar.delegate = self
    self.myTableView.delegate = self


    self.navigationController?.extendedLayoutIncludesOpaqueBars = true

    //self.myTableView.reloadData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
{
    searchBar.resignFirstResponder()
   // self.navigationController?.navigationBar.isHidden = false
    self.mySearchBar.endEditing(true)
    print("Search word = \(searchBar.text)")

    let query = PFQuery(className:"myClass")
    //let newText = searchBar.autocapitalization
    searchBar.autocapitalizationType = .none
    searchBar.text = searchBar.text?.localizedLowercase
    query.whereKey("collegeNickName", contains: searchBar.text)

    query.findObjectsInBackground { (results, error) in
        if error == nil {

            if let objects = results {

                self.searchResults.removeAll(keepingCapacity: true)

                for object in objects {
                    let firstName = object.object(forKey: "myName") as! String
                    let image = object.object(forKey: "myImage") as! PFFile
                    //   let lastName = object.object(forKey: "myPlace") as! String
                    //   let fullName = firstName + " " + lastName
                    self.searchResults.append(firstName)

                    print(self.searchResults[0])
                    DispatchQueue.main.async {
                        self.myTableView.reloadData()
                        self.mySearchBar.resignFirstResponder()
                    }
                }
            }

        } else {

            let myAlert = UIAlertController(title:"Alert", message:error?.localizedDescription, preferredStyle:UIAlertControllerStyle.alert)

            let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)

            myAlert.addAction(okAction)

            self.present(myAlert, animated: true, completion: nil)
            return


                }
            }
        }

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    //self.navigationController?.navigationBar.isHidden = true
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return searchResults.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "myCell")

    let myCell = myTableView.dequeueReusableCell(withIdentifier: "myCell")

    myCell?.textLabel?.text = searchResults[indexPath.row]
    print(searchResults[indexPath.row])
    return myCell!
}


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("Hi")
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar)
{
    mySearchBar.resignFirstResponder()
    mySearchBar.text = ""
    myTableView.reloadData()
}

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
    //self.mySearchBar.resignFirstResponder()
    //self.mySearchBar.endEditing(true)
    self.definesPresentationContext = true
}

@IBAction func refreshButtonTapped(sender: AnyObject) {
    mySearchBar.resignFirstResponder()
    mySearchBar.text = ""
    self.searchResults.removeAll(keepingCapacity: false)
    self.myTableView.reloadData()
  }
}

Также он реализует searchView. Я получаю то, что хочу найти, но не могу использовать методы выбора и отмены выбора в моем классе.

4 ответа

Решение
self.myTableView.dataSource = self
self.myTableView.delegate = self

<--- добавь это.

В Интерфейсном Разработчике

  • соединять dataSource а также delegate из My Table View в SearchClass

Тогда вы можете удалить избыточный self.myTableView.dataSource = self в SearchClass

Учтите, что соединения в Интерфейсном Разработчике более эффективны, чем в коде.

Заметил, что вы установили делегата в раскадровке как view вместо вашего UIViewController увидеть Откройте для себя - это мое UViewController

Объявление клетки неверно. Вы сделали это ниже кода

 let myCell = myTableView.dequeueReusableCell(withIdentifier: "myCell")

Правильный формат

 let myCell = tableView.dequeueReusableCell(withIdentifier: "myCell")

Причина: когда вы используете свойство dequeue, то UITableView лишить свою клетку по параметру, который он получил от метода

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

видите, есть парам tableView но вы выходите из UITableView,

Другие вопросы по тегам