我的每个UITableViewCells中都有一个按钮。按下时,我需要获取其IndexPath。
我的解决方法是获取UITouch的位置,并使用indexPathForRow(at:CGPoint)获取包含按钮的单元格的indexPath。问题在于,这仅返回IndexPath [0, 0]。
@objc func favoriteButtonPressed(_ sender: CellButton, event: UIEvent) {
//gets location of touch
let events = event.touches(for: sender)
var location : CGPoint = CGPoint(x: 0, y: 0)
for event in events! {
location = event.location(in: sender)
print("\(location)")
//prints legitimate location ex. (30.0,23.5)
}
//An attempt at getting an IndexPath other than [0,0]. Does not affect result.
let convertedLocation = tableView.convert(location, from: view)
//Returns [0,0] no matter where the touch is located
let favoriteIndexPath : IndexPath = tableView.indexPathForRow(at: convertedLocation)!
//Returns the first cell no matter what as a result
let unFavoritedCell : UITableViewCell? = tableView(tableView, cellForRowAt: favoriteIndexPath)
}
虽然结果应为[0,(按钮所在的行)],但结果始终为[0,0]。
关于为什么发生这种情况的任何想法?
如果您需要查看代码的其他任何部分,请告诉我。谢谢。