【发布时间】:2018-02-16 01:32:04
【问题描述】:
好的,所以我有一个带有UITableView 的 ViewController。在继续编码之前,我读到为了从按钮获取操作或拥有自定义单元格,您可以使用标签或使用协议和委托的更清洁的解决方案。显然我选择了后者。
现在,当我在我的班级 ViewController 中使用称为 TableViewCellsDelegate 的自定义 UITableViewCell 时,我需要在下面的代码中将其替换为 UITableViewDelegate,如您所见:
class ViewController: UIViewController , UITableViewDataSource, TableViewCellsDelegate{} ....
我的问题是我现在没有调用这个函数:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("in here")
if indexPath.row == 0 {
if dateCellExpanded {
dateCellExpanded = false
} else {
dateCellExpanded = true
}
tableView.beginUpdates()
tableView.endUpdates()
}
}
我怀疑如果您选择自定义 UITableViewCell 会丢失一些委托功能。必须有一些解决方案。这是我的TableViewCellsDelegate
protocol TableViewCellsDelegate : class {
func bookTapped(_ sender: UIButton)
func unbookTapped(_ sender: UIButton)
}
class TableViewCells: UITableViewCell {
@IBOutlet var bookButtonProperties: UIButton!
@IBOutlet var unbookButtonProperties: UIButton!
@IBOutlet var nameField: UITextField!
@IBOutlet var numberField: UITextField!
weak var delegate: TableViewCellsDelegate?
@IBAction func bookPressed(_ sender: UIButton) {
delegate?.bookTapped(sender)
}
@IBAction func unbookPressed(_ sender: UIButton) {
delegate?.unbookTapped(sender)
}
}
【问题讨论】:
-
tableView(_:didSelectRowAt:)是UITableViewDelegate的一个方法。因此,您需要遵守UITableViewDelegate才能在tableView(_:didSelectRowAt:)内部进行回调 -
didSelectRowAt将在您选择单元格时被调用,但在您的情况下,您有像UIButton和UITextField这样的控件,它们派生自UIControl,这意味着当您点击这些控件时控制您的水龙头不会进入单元格,这会导致tableView(_:didSelectRowAt:)未被调用。另一方面,UITableView 委托可能未正确设置为viewController -
这不是@deoKasuhal 的情况,正如我所说的,当我将我的“ViewController”从 TableViewCellsDelegate 更改为 UITableViewDelegate 时,然后调用了 didSelect(你提到的所有插座都还在)。所以我知道我需要 UITableViewDelegate 但是我正在寻找解决这个问题的方法还是我必须改造我的编码
-
@TimoCengiz,
UITableViewDelegate与UITableView关联,TableViewCellsDelegate与UITableViewCell关联。委托的代码应该设置为ViewController,一个使用UITableView,另一个使用UITableViewCellincellForRowAtIndexPath。查看代码缺少一件事,即您没有将UITableViewDelegate扩展到您的viewController。class ViewController: UIViewController , UITableViewDataSource, TableViewCellsDelegate, UITableViewDelegate {} -
@deoKasuhal 好的,所以我很生气。我记得尝试输入“UITableViewDelegate”,但出现错误,所以我认为这是不可能的。当我读到你的推荐时,我觉得'UITableViewDelegate' 的位置很重要。如果我输入的顺序是:'UIViewController,'UITableViewDataSource','UITableViewDelegate','TableViewCellsDelegate',为什么我会收到错误?否则谢谢它现在有效。这就是为什么我不明白其他人的原因,因为我觉得我已经尝试过了。
标签: swift uitableview swift3 didselectrowatindexpath