Как скрыть табличное представление после выбора строки - PullRequest
0 голосов
/ 28 февраля 2019

У меня есть textField, который при касании отображает tableView с несколькими строками.

Я пытаюсь сделать это: когда пользователь выбирает одну из строк, значение строки помещается в textField, а tableView закрывается.

Первая часть хорошо работает длямне.Пользователь касается одной строки, и textField показывает значение этой строки.Но если я хочу закрыть табличное представление, я должен дважды нажать на строку.

Это мой код:

class Redactar_mensaje: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {


    var values = ["123 Main Street", "789 King Street", "456 Queen Street", "99 Apple Street", "red", "orange", "yellow", "green", "blue", "purple", "owaldo", "ostras", "Apple", "Pineapple", "Orange", "Adidas"]

@IBOutlet weak var campo_para: UITextField!
@IBOutlet weak var tableView: UITableView!

    var originalCountriesList:[String] = Array()

override func viewDidLoad() {
        super.viewDidLoad()

        tableView.isHidden = true


        for country in values {
           originalCountriesList.append(country)
        }

        campo_para.delegate = self
        tableView.delegate = self
        tableView.dataSource = self

        campo_para.addTarget(self, action: #selector(textFieldActive), for: UIControlEvents.touchDown)
        campo_para.addTarget(self, action: #selector(searchRecords(_ :)), for: .editingChanged)
    }


    @objc func searchRecords(_ textField: UITextField) {
        self.values.removeAll()
        if textField.text?.count != 0 {
            for country in originalCountriesList {
                if let countryToSearch = textField.text{
                    let range = country.lowercased().range(of: countryToSearch, options: .caseInsensitive, range: nil, locale: nil)
                    if range != nil {
                        self.values.append(country)
                    }
                }
            }
        } else {
            for country in originalCountriesList {
                values.append(country)
            }
        }

        tableView.reloadData()
    }



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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cellx")
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "cellx")
        }
        cell?.textLabel?.text = values[indexPath.row]
        return cell!
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        campo_para.text = values[indexPath.row]

        tableView.isHidden = true //I need press twice for this. I want press only one

    }


    func textFieldActive() {
        tableView.isHidden = false
    }

}

В идеале, пользователь касается textField, отображает tableView,выбирает одно из значений, и оно автоматически закрывает tableView.Но этот последний не работает хорошо.

Любой совет?

Ответы [ 2 ]

0 голосов
/ 28 февраля 2019

Здесь я привожу свое решение, на случай, если кто-то еще произойдет нечто подобное.

Просто измените порядок строк и добавьте еще одну строку.Сначала он делает его невидимым, а затем помещает результат в textField, и он волшебным образом работает!

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

        tableView.isHidden = true
        campo_para.text = NombreUsuario[indexPath.row]
        campo_asunto.becomeFirstResponder()

    }

Спасибо!

0 голосов
/ 28 февраля 2019

Детали

xCode 8.3, Swift 3.1

Пример обнаружения двойного и одиночного касания TableViewCell

ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.tableFooterView = UIView()
    }
}

extension ViewController: UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
        cell.label.text = "\(indexPath)"
        cell.delegate = self
        return cell
    }
}

extension ViewController:TableViewCellDelegate {


    func tableViewCell(singleTapActionDelegatedFrom cell: TableViewCell) {
        let indexPath = tableView.indexPath(for: cell)
        print("singleTap \(String(describing: indexPath)) ")
    }

    func tableViewCell(doubleTapActionDelegatedFrom cell: TableViewCell) {
        let indexPath = tableView.indexPath(for: cell)
        print("doubleTap \(String(describing: indexPath)) ")
        //You can hide your textfield here
    }
}

TableViewCell.swift

import UIKit

class TableViewCell: UITableViewCell {

    @IBOutlet weak var label: UILabel!
    private var tapCounter = 0
    var delegate: TableViewCellDelegate?


    override func awakeFromNib() {
        super.awakeFromNib()

        let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        addGestureRecognizer(tap)
    }

    func tapAction() {

        if tapCounter == 0 {
            DispatchQueue.global(qos: .background).async {
                usleep(250000)
                if self.tapCounter > 1 {
                    self.doubleTapAction()
                } else {
                    self.singleTapAction()
                }
                self.tapCounter = 0
            }
        }
        tapCounter += 1
    }

    func singleTapAction() {
        delegate?.tableViewCell(singleTapActionDelegatedFrom: self)
    }

    func doubleTapAction() {
        delegate?.tableViewCell(doubleTapActionDelegatedFrom: self)
    }
}

TableViewCellDelegate.swift

import UIKit

protocol TableViewCellDelegate {
    func tableViewCell(singleTapActionDelegatedFrom cell: TableViewCell)
    func tableViewCell(doubleTapActionDelegatedFrom cell: TableViewCell)
}

Результат

enter image description here

...