【发布时间】:2018-08-09 04:36:25
【问题描述】:
我有一个带有自定义单元格的 UITableView。自定义单元格为三个按钮,覆盖整个单元格。我正在尝试根据用户选择的标签自动滚动表格视图。
我尝试使用 NotificationCenter,但在尝试滚动时它会崩溃。有没有更优雅的解决方案?
编辑:我的最终目标是让用户点击 optionOne 并让它滚动到紧邻下方的单元格。诀窍是在没有 cellForRowAt 的情况下执行此操作,因为由于有多个按钮,我在单元格中处理它。
自定义单元格:
@IBOutlet weak var optionOneLabel: UILabel!
@IBOutlet weak var optionTwoLabel: UILabel!
@IBOutlet weak var optionThreeLabel: UILabel!
override func prepareForReuse() {
super.prepareForReuse()
let optionOne = UITapGestureRecognizer(target: self, action: #selector(CustomCell.optionOnePressed(_:)))
optionOneLabel.addGestureRecognizer(optionOne)
let optionTwo = UITapGestureRecognizer(target: self, action: #selector(CustomCell.optionTwoPressed(_:)))
optionTwoLabel.addGestureRecognizer(optionTwo)
let optionThree = UITapGestureRecognizer(target: self, action: #selector(CustomCell.optionThreePressed(_:)))
optionThreeLabel.addGestureRecognizer(optionThree)
}
@objc func optionOnePressed(_ sender: UITapGestureRecognizer) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "scrollTableOptionOne"), object: nil)
}
@objc func optionTwoPressed(_ sender: UITapGestureRecognizer) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "scrollTableOptionTwo"), object: nil)
}
@objc func optionThreePressed(_ sender: UITapGestureRecognizer) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "scrollTableOptionthree"), object: nil)
}
TableViewController
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(optionOne), name: NSNotification.Name(rawValue: "scrollTableOptionOne"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(optionTwo), name: NSNotification.Name(rawValue: "scrollTableOptionTwo"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(optionThree), name: NSNotification.Name(rawValue: "scrollTableOptionThree"), object: nil)
}
@objc func optionOne() {
let indexPath = NSIndexPath(item: posts.count, section: 0)
tableView.scrollToRow(at: indexPath as IndexPath, at: UITableViewScrollPosition.init(rawValue: indexPath.row + 2)!, animated: true)
}
@objc func optionTwo() {
print("Don't scroll this one for now")
}
@objc func optionThree() {
print("Don't scroll this one for now")
}
如果您需要更多信息,请告诉我。谢谢。
【问题讨论】:
-
你是单节还是多节?
-
崩溃报告说什么?另外,不要在
prepareForReuse中添加通知,因为您最终会添加多个相同类型的手势,因为您没有删除第一次添加的手势。
标签: ios swift uitableview