【问题标题】:handling button in prototype cell in tableview in swift 2swift 2中tableview中原型单元格中的处理按钮
【发布时间】:2016-08-05 16:01:23
【问题描述】:

我找不到如何处理 tableview 中的按钮。好的,我有一个表格视图,它显示了一些值,比如 100 个硬币,50 个硬币......并且右侧有按钮。所以问题是当你按下那个按钮时,那个按钮怎么知道你已经点击了特定值的按钮?可以发一些地方和代码。

该按钮应该执行购买产品的消息

【问题讨论】:

    标签: ios uitableview uibutton swift2


    【解决方案1】:

    在你的控制器中创建一个方法,即

    func btnClickAction(sender: UIButton)
    {
        var superView = sender.superview
    
        while superView?.isKindOfClass(UITableViewCell) == false
        {
            superView = superView?.superview
        }
    
        var cell = superView as! UITableViewCell
        var indexPath = self.tableView.indexPathForCell(cell)! as NSIndexPath
    }
    

    通过上述方法的indexPath,你会发现你在哪个单元格中被点击了。

    在您的cellForRowAtIndexPath 中,您需要将按钮的目标添加到上述方法中,即

    btn.addTarget(self, action: "btnClickAction", forControlEvents: UIControlEvents.TouchDragInside)
    

    【讨论】:

    • 感谢您的来信。我不知道为什么人们会用-2来提问
    【解决方案2】:

    我知道这有点晚了,但我真的很喜欢这个解决方案,所以我希望它对某人有所帮助!这是@Jatin Chauhan 的答案,但已更新。

    斯威夫特 3

    @IBAction func actionFromButtonPress(_ sender: Any) {
    
        var superView = (sender as AnyObject).superview
    
        while type(of: (superView!)!) != UITableViewCell.self
        {
            superView = (superView as AnyObject).superview
        }
    
        let cell = superView as! UITableViewCell
        let indexPath = self.tableView.indexPath(for: cell)! as NSIndexPath
        let correspondingDataInDataSource = self.tableViewDataSource[indexPath.row]
    
            self.tableView.reloadData()
    }
    

    使用它,您可以将 xib 或情节提要中的按钮连接到此处的 IBAction。

    注意:如果您像我一样有自定义 UITableViewCell,则不应将类型与“UITableViewCell.self”进行比较,而应将其与“YourCustomTableViewCellClass.self”进行比较。

    注意 2:请注意,对于 while 循环,我需要解包两次。当我把它打印出来时,它是一个可选的,通过打开它,类型可以正确地相互比较。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多