【问题标题】:Dismiss modal if anywhere but UITableViewCell is touched如果触摸 UITableViewCell 以外的任何地方,则关闭模式
【发布时间】:2018-01-05 23:09:16
【问题描述】:

我有一个带有 UITableView 的模式。如果触摸屏幕上的任何位置(表格视图内的 UITableViewCells 除外),我想关闭模式。但是,您不能为 UITableView 单元格创建一个插座以在代码中引用它。目前我有这个代码:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch: UITouch? = touches.first

    if touch?.view != WHAT TO PUT HERE? {
        dismiss(animated: true, completion: nil)
    }
}

我不确定如何引用 UITableViewCells。我该怎么做?

【问题讨论】:

  • 通常我会在表格视图后面的视图上放置一个手势识别器。单元格将捕获其中发生的任何触摸,并且在手势识别器中,您可以以某种方式关闭模式。
  • 我在 tableview 的超级视图中添加了一个手势识别器,但单元格没有捕获触摸。是否有我应该添加手势识别器的特定视图?
  • 在 UITableView 后面添加一个大按钮。并在按钮单击时关闭模式
  • 我的表格视图占据了整个屏幕,即使单元格没有,所以表格视图后面的元素永远不会被触及。

标签: ios swift uitableview


【解决方案1】:

我找到了一个可行的解决方案。我不得不使用这种方法调整 tableView 的大小以适应其内容的大小:

override func viewDidAppear(_ animated: Bool) {
    //Resize the tableView height to the height of its content.
    tableView.frame.size.height = soundTableView.contentSize.height

    //Set the origin of tableView to the bottom of the screen minus a 30px margin
    //(this was my tableView's original position before resizing)
    tableView.frame.origin.y = self.view.frame.size.height - soundTableView.frame.size.height - 30
}

然后我有这个方法,如果除了 tableView 被触摸之外的任何地方,它都会关闭模式:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch: UITouch? = touches.first

    if touch?.view != tableView {
        dismiss(animated: true, completion: nil)
    }
}

【讨论】:

    猜你喜欢
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 2016-02-11
    • 2014-04-13
    • 2020-05-06
    • 1970-01-01
    相关资源
    最近更新 更多