我有一个简单的桌子,里面有几个单元格,里面有一个标签和一个圆圈。我想根据水龙头(单人或双人)更改标签。为此我需要知道单元格的indexPath,所以我添加了委托。点击被识别但是当我尝试将有关单元格的信息推送到ViewController时(函数tableViewCell(singleTapActionDelegatedFrom& doubleTapActionDelegatedFrom)似乎无法正常工作
ViewController.swift:
import UIKit
var elements: [[Int16]] = Array(repeating:Array(repeating:0, count:2), count:10)
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
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)) ")
}
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
}
cell.delegate? = self as! TableViewCellDelegate
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()
tableView.dataSource = self
tableView.tableFooterView = UIView()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
@IBOutlet weak var tableView: UITableView!
}
TableViewCell.swift:
import UIKit
class TableViewCell: UITableViewCell
{
var delegate: TableViewCellDelegate?
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)
}
@objc 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)
}
@IBOutlet weak var Label: UILabel!
@IBOutlet weak var Circle: UIView!
}
TableViewCellDelegate:
protocol TableViewCellDelegate
{
func tableViewCell(singleTapActionDelegatedFrom cell: TableViewCell)
func tableViewCell(doubleTapActionDelegatedFrom cell: TableViewCell)
}