【问题标题】:action upon selecting cell in segmented control在分段控制中选择单元格时的操作
【发布时间】:2020-02-19 03:15:26
【问题描述】:

我正在使用下面的代码来完成在分段控制中选择单元格以执行 segue 并相应地传递信息时完成的操作,但它没有按预期执行,它在被点击的单元格上没有做任何事情。

下面的代码是通过扩展实现的

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) -> UITableViewCell {
        print("hello1")
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyWsPostCell
        switch segmentControl.selectedSegmentIndex{
        case 0:
            print("hello2")
            cell.section1 = section1list[indexPath.row]
            cell.commentbutton.tag = indexPath.row
            cell.commentbutton.addTarget(self, action: #selector(todetailview(_:)), for: .touchUpInside)

            break
        case 1:
            print("hello4")
            cell.section2 = section2list[indexPath.row]
            cell.commentbutton.tag = indexPath.row
            cell.commentbutton.addTarget(self, action: #selector(todetailview(_:)), for: .touchUpInside)

            break

        default:
            break
        }

        return cell
    }

函数调用

    @objc func todetailview(_ sender: AnyObject) {

              performSegue(withIdentifier: "myWtoDetail", sender: self)

          }


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            var vc = segue.destination as! DetailViewController
            vc.infopassed = infokey

     }

如果需要更多信息,请告诉我

【问题讨论】:

  • 你把delegate设置成tableView了吗?
  • @AjinkyaSharma 是的,我已经这样做了,已经根据需要执行了一个 segue,这是关于必须点击单元格的第二个 segue
  • 好的,首先你将目标添加到 didSelectRow 中的按钮。那不会调用 action 方法。
  • 是否调用了 didSelectRow?
  • @AjinkyaSharma 如何确保 didSelectRow 被调用?抱歉,我正在学习 swift

标签: ios swift uitableview segue uisegmentedcontrol


【解决方案1】:

因为您点击的是Button 而不是您的cell,所以didSelect 可能没有被调用,因为Button 覆盖了您的cell。你可以使用更近的。

您的表格视图单元格类

class XYZ : UITableViewCell {

  var btn1:(()->())?

  //Create Action For Button 
  @IBAction func btnAction(_ sender: Any) {
     btn1?()
   }
}

在您的 tableView 中:cellForRowAt 方法

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier:.....

     cell.btn1 = {
            ()in
         // You can Perform your action here. No need to maintain any tag or index 

      }
    }

【讨论】:

  • 这可以与“@IBOutlet weak var celltap: UIView!”一起使用吗?而不是 UIButton?
  • 没有。您必须将点击手势添加到您的视图中。或者请解释一下你到底想做什么。
  • 是的,我需要给单元格添加点击手势,这样每当用户点击除了按钮之外的单元格时,它都会执行一定的segue以及一定的数据传递,请指导我如何添加点击手势
  • 你能告诉我你的设计层次结构或故事板截图吗?请记住,如果您正在点击单元格,则无需添加任何手势即可使用 didselect 方法
  • 并将您的按钮目标添加到您的cellForRow 而不是didSelectRow
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
  • 2019-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多