【问题标题】:swift UIButton click unavailable out of tableview cellswift UIButton单击在tableview单元格中不可用
【发布时间】:2018-04-18 15:36:16
【问题描述】:

以下代码,点击事件有效。

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "SwiftCell")

    let button = UIButton()
    button.setTitle(hiddenGear ? "+" : "-", for: .normal)
    button.setTitleColor(UIColor.lightGray, for: .normal)
    button.addTarget(self, action:#selector(self.toggleGear), for: .touchUpInside)
    button.frame = CGRect(x: self.view.frame.width - 36, y: 0, width: 30, height: 30)
    button.backgroundColor = UIColor.red
    cell.addSubview(button)

但我想要的是如下所示:

将UIButton移出uitableview单元格,点击事件不起作用。

button.frame = CGRect(x: self.view.frame.width - 36, y: -30, width: 30, height: 30)

尝试使用 cell.bringSubview(toFront: button) ,但它也不起作用。有什么想法吗?

【问题讨论】:

  • 你在哪里添加这个代码???
  • @Sh_Khan 更新了我的问题

标签: swift uitableview uibutton swift4


【解决方案1】:

这是非法的:

cell.addSubview(button)

您不能向单元格添加视图。您必须仅将视图添加到单元格的contentView

但内容视图并没有一直向右延伸。如果您希望视图一直位于右侧,则必须将其作为辅助视图提供。

最后,你不能轻易地在单元格边界之外添加一个工作按钮,因为它的父视图边界之外的子视图是不可触摸的。但是,您可以通过修改超级视图的命中测试来使其可触摸。您需要重写此方法:

https://developer.apple.com/documentation/uikit/uiview/1622469-hittest

【讨论】:

    【解决方案2】:

    您需要使用相对于UITableViewCell 顶部的约束。另外,我可以看到您正在尝试在角落创建一个“+”(加号)图标。考虑使用对象库中的Navigation Item

    【讨论】:

      【解决方案3】:

      首先,由于重用,不建议在 cellForRow 中添加 UI 元素,其次,如果按钮应该在每个单元格中,您可以将按钮封装在单元格内并使用背景颜色来假装它不在单元格中,否则你必须相对于mainView(self.view)添加它

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多