我试图在手势 View 点击时更改我的表格 View 单元格内容,但是我收到了错误
线程1:信号SIGABRT
无法将“UILabel”类型的值 (0x117f4ad68) 转换为“MyApplication.Read”
func ReadAnswer(_ sender: UIGestureRecognizer) {
let CellIndex = sender.view?.tag
print(CellIndex!)
let test = sender.view as! Read! // This produces error
test?.comment.text = "You have clicked on cell \(CellIndex)"
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let mycell = tableView.dequeueReusableCell(withIdentifier: "Read", for: indexPath) as! Read
mycell.comment.tag = indexPath.row
mycell.comment.text = streamsModel.Posts[indexPath.row]
let Gesture = UITapGestureRecognizer(target: self, action: #selector(ReadAnswer(_:)))
Gesture.delegate = self as? UIGestureRecognizerDelegate
mycell.comment.addGestureRecognizer(Gesture)
return cell
}
再次在标签上单击我想更改该标签的内容,以说明您已单击单元格 (CellIndex)。我可以在每次点击时获得正确的索引,但是在 Let Test 上它给出了一个错误。
最佳答案
您已将 Gesture
添加到 UILabel
..!! comment
是 UILabel
。
let Gesture = UITapGestureRecognizer(target: self, action: #selector(ReadAnswer(_:)))
Gesture.delegate = self as? UIGestureRecognizerDelegate
mycell.comment.addGestureRecognizer(Gesture)
在Gesture Action
中,sender.view应该是UILabel。所以出现了下面的错误。
无法将“UILabel”类型的值 (0x117f4ad68) 转换为“MyApplication.Read”
func ReadAnswer(_ sender: UIGestureRecognizer) {
let CellIndex = sender.view?.tag
print(CellIndex!)
let test = sender.view as! Read! // This produces error
test?.comment.text = "You have clicked on cell \(CellIndex)"
}
求解
我们必须为此使用字典。所以,我们可以避免 tableView 的重用。你可以拿到我的answer对于 UIStepper。同样的逻辑如下。
var textDict = [Int : String]()
override func viewDidLoad() {
super.viewDidLoad()
for i in 0..<70 // numberOfRows
{
textDict[i] = "Hello"
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 70
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "table", for: indexPath) as! TblTableViewCell
let Gesture = UITapGestureRecognizer(target: self, action: #selector(ReadAnswer))
Gesture.delegate = self as? UIGestureRecognizerDelegate
cell.commentLbl.tag = indexPath.row
cell.commentLbl.isUserInteractionEnabled = true
cell.commentLbl.addGestureRecognizer(Gesture)
cell.commentLbl.text = textDict[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
@objc func ReadAnswer(_ sender: UIGestureRecognizer) {
let CellIndex : Int = (sender.view?.tag)!
textDict[CellIndex] = "You have clicked on cell \(CellIndex)"
tblView.reloadData()
}
关于swift - 如何将 View TableViewCell 转换为 UIGestureView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48818908/