Как распознать, какая ячейка была прослушена один раз, а какая - дважды - PullRequest
0 голосов
/ 15 мая 2018

есть! Я хотел бы узнать, какая ячейка прослушивается один раз, а какая - дважды. У меня есть два класса, один для TableViewController и другой для TableViewCell. Я хотел бы манипулировать ячейками относительно касания, но я не могу получить их indexPath.

TableViewController:

import UIKit

var elements: [[Int16]] = Array(repeating:Array(repeating:0, count:2), count:10)

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return elements.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell

    if(elements[indexPath.row][1] == 1) //if red
    {
        cell.Label.text = String(elements[indexPath.row][0] * 3)
        cell.Circle.backgroundColor = UIColor.red
    }
    else //if blue
    {
        cell.Label.text = String(elements[indexPath.row][0])
        cell.Circle.backgroundColor = UIColor.blue
    }

    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
    return UIScreen.main.bounds.height/10
}

override func viewWillAppear(_ animated: Bool)
{
    for i in 0..<elements.count
    {
        elements[i][0] = Int16(Int(arc4random_uniform(10)))
        elements[i][1] = Int16(Int(arc4random_uniform(2)))
    }

    Memory().save(entity: elements)
}

override func viewDidLoad()
{
    super.viewDidLoad()
}

override func didReceiveMemoryWarning()
{
    super.didReceiveMemoryWarning()
}

}

TableViewCell:

import UIKit

class TableViewCell: UITableViewCell

{

override func awakeFromNib()
{
    super.awakeFromNib()

    Circle.layer.cornerRadius = Circle.frame.width / 2

    let singleTap = UITapGestureRecognizer(target: self, action: #selector(tappedOnce))
    singleTap.numberOfTapsRequired = 1
    addGestureRecognizer(singleTap)

    let doubleTap = UITapGestureRecognizer(target: self, action: #selector(tappedTwice))
    doubleTap.numberOfTapsRequired = 2
    addGestureRecognizer(doubleTap)

    singleTap.require(toFail: doubleTap)
    singleTap.delaysTouchesBegan = true
    doubleTap.delaysTouchesBegan = true
}

override func setSelected(_ selected: Bool, animated: Bool)
{
    super.setSelected(selected, animated: animated)
}

@objc func tappedOnce(sender: AnyObject?)
{
        print("1111111")
        //Memory().reload(reload: x, I: x)
}

@objc func tappedTwice()
{
    print("2222222")
}

@IBOutlet weak var Label: UILabel!
@IBOutlet weak var Circle: UIView!

}

Внутри ячеек у меня есть метка, на которой хранится случайное число (метка) от 0 до 10, рядом с которым находится круг - синий или красный (они также случайны при запуске). Если кружок красного цвета, то число (метка) показывает число, умноженное на три. Все это есть.

Теперь ... Я хочу изменить число, коснувшись ячейки один раз, и сделать ее 0, коснувшись ее дважды

1 Ответ

0 голосов
/ 15 мая 2018

TableViewController:

var elements: [[Int16]] = Array(repeating: Array(repeating:0, count:2), count:10)

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    //MARK: - UIViewController LifeCycle
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        for i in 0..<elements.count {
            elements[i][0] = Int16(Int(arc4random_uniform(10)))
            elements[i][1] = Int16(Int(arc4random_uniform(2)))
        }
        Memory().save(entity: elements)
    }


    //MARK: - UITableView Delegate & DataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return elements.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell

        if elements[indexPath.row][1] == 1 {
            cell.Label.text = String(elements[indexPath.row][0] * 3)
            cell.Circle.backgroundColor = UIColor.red
        }
        else {
            cell.Label.text = String(elements[indexPath.row][0])
            cell.Circle.backgroundColor = UIColor.blue
        }
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UIScreen.main.bounds.height/10
    }
}

TableViewCell:

class TableViewCell: UITableViewCell {

    @IBOutlet weak var Label: UILabel!
    @IBOutlet weak var Circle: UIView!
    private var tapCounter = 0

    override func awakeFromNib() {
        super.awakeFromNib()

        Circle.layer.cornerRadius = Circle.frame.width / 2

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

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

    @objc func tapAction() {

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

    func tappedOnce() {
        print("1111111")
    }
    func tappedTwice() {
        print("2222222")
    }
}

Возьмите отсюда ссылку Одинарные и двойные нажатия на UITableViewCellв Свифт 3

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...