如何在 cell.swift 中获取 indexPath.row [英] How can I get indexPath.row in cell.swift
问题描述
我有 2 个文件.
- myTableViewController.swift
- myTableCell.swift
我可以在 myTabelCell.swift 函数中获取 indexPath.row 吗?
Can I get the indexPath.row in myTabelCell.swift function?
这里是 myTableCell.swift
Here is myTableCell.swift
import UIKit
import Parse
import ActiveLabel
class myTableCell : UITableViewCell {
//Button
@IBOutlet weak var commentBtn: UIButton!
@IBOutlet weak var likeBtn: UIButton!
@IBOutlet weak var moreBtn: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
}
@IBAction func likeBtnTapped(_ sender: AnyObject) {
//declare title of button
let title = sender.title(for: UIControlState())
//I want get indexPath.row in here!
}
这里是 myTableViewController.swift
Here is myTableViewController.swift
class myTableViewController: UITableViewController {
//Default func
override func viewDidLoad() {
super.viewDidLoad()
//automatic row height
tableView.estimatedRowHeight = 450
tableView.rowHeight = UITableViewAutomaticDimension
}
// cell config
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//define cell
let cell = tableView.dequeueReusableCell(withIdentifier: "myTableCell", for: indexPath) as! myTableCell
}
如您所见...我正在尝试在 myTableCell 中获取 indexPath.row,liktBtnTapped 函数.
As you can see... I'm trying to get indexPath.row in myTableCell, liktBtnTapped function.
你能告诉我如何访问或获取 IndexPath.row 吗?
Could you let me know how can I access or get IndexPath.row?
推荐答案
我创建了一个带有递归方法的 UIResponder
扩展,你可以在任何 UIView
(它继承自 UIResponder
) 以查找特定类型的父视图.
I have created a UIResponder
extension with a recursive method that you can use in any UIView
(which inherits from UIResponder
) to find a parent view of a specific type.
import UIKit
extension UIResponder {
/**
* Returns the next responder in the responder chain cast to the given type, or
* if nil, recurses the chain until the next responder is nil or castable.
*/
func next<U: UIResponder>(of type: U.Type = U.self) -> U? {
return self.next.flatMap({ $0 as? U ?? $0.next() })
}
}
使用它,我们可以扩展 UITableViewCell
为表格视图和单元格的索引路径提供一些方便的只读计算属性.
Using this, we can extend UITableViewCell
with some convenient read-only computed properties for the table view and index path of the cell.
extension UITableViewCell {
var tableView: UITableView? {
return self.next(of: UITableView.self)
}
var indexPath: IndexPath? {
return self.tableView?.indexPath(for: self)
}
}
以下是您在示例中的使用方法:
Here is how you could use it in your example:
@IBAction func likeBtnTapped(_ sender: AnyObject) {
//declare title of button
let title = sender.title(for: UIControlState())
//I want get indexPath.row in here!
self.indexPath.flatMap { print($0) }
}
这篇关于如何在 cell.swift 中获取 indexPath.row的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!