【发布时间】:2018-06-24 10:07:34
【问题描述】:
当点击单元格中的按钮时,我正在努力如何检索 UITableViewCell 的 indexPath。我正在为按钮使用典型的委托代码。我已经用谷歌搜索并对此进行了实验,但我无法得到它。这是我的自定义 Tableview 单元格代码:
import UIKit
protocol MainTableViewCellDelegate {
func tappedReport(id: String)
}
class MainTableViewCell: UITableViewCell {
@IBOutlet weak var cellView: UIView!
@IBOutlet weak var userLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var postLabel: UILabel!
var postItem: PostData!
var delegate: MainTableViewCellDelegate?
func setPost(post: PostData) {
postItem = post
let ourPost = postItem.postId
print(ourPost)
}
@IBAction func reportButton(_ sender: UIButton) {
delegate?.tappedReport(id: postItem.postId)
//print("Reported post ID: \(postItem.postId)")
}
}
// View controller/ cellforRowat
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! MainTableViewCell
cell.postLabel.text = posts[indexPath.row].message
cell.textLabel?.adjustsFontSizeToFitWidth = true
cell.layer.cornerRadius = 8
cell.userLabel.text = posts[indexPath.row].username
cell.delegate = self
cell.getIndexPath()
}
extension ViewController: MainTableViewCellDelegate {
func tappedReport(id: String) {
print("Hi")
AlertController.showAlert(inViewController: self, title: "Report", message: "Report button tapped.")
}
}
还有什么想法?
【问题讨论】:
-
点击单元格中的按钮时会发生什么?您是否遇到了您不想要的错误或行为?看来,如果您尝试识别被窃听的单元格,那么使用标准
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)将是最简单的方法。然后,您可以轻松获取其中按钮的属性以发送到您的tappedReport方法。 -
实际上 Kane Cheshire 的答案有效,但由于某种原因,当我点击按钮时它一直保持 nil 。如果它取出'postItem.postId',并用随机(“hi”)替换它,那么它工作正常。我现在也正在获取 indexPath,所以我想我将能够以不同的方式找到 .postId。
-
不相关,但您可能希望将您的协议定义为
class协议(例如protocol MainTableViewCellDelegate: class { ... })并将您的delegate定义为weak(例如weak var delegate: MainTableViewCellDelegate?)。否则,您将有一个强大的参考周期。