如何通过单击单独的UIViewController的UITableViewCell按钮创建UIView?

问题描述

我正在使用Xcode / Swift开发iOS应用,并且尝试在单独的UISendViewButton按钮中单击时在MainViewController添加子视图UITableViewCell {1}}(本身嵌入在UITableViewController中)。基本上,该概念是类似于Instagram中的“发送帖子”按钮的概念:用户将单击纸飞机按钮,并显示一个单独的朋友列表(UIView-> UIView)。联系人列表旁边有一个按钮(UITableViewController),用户可以单击该按钮以选择将其发送给哪些朋友。我想要的是只有在用户决定单击其朋友姓名旁边的按钮(customButton时,才会出现“发送”按钮(UIViewButton)。

我可以通过将customButton嵌入UITableViewController并将其作为子视图添加UIView中来使其出现,但是当我单击MainViewController时在customButton类中,什么都没有发生。我想在点击UITableViewCell时出现一个新的UIViewButton(在我的MainViewController中)。

所以基本上我想知道如何让这两个控制器通信。容纳customButton按钮的控制器是Xcode库提供的控制器:UITableViewCell-> UITableViewController-> UITableView本身嵌入在{{1}中}。

我尝试在下面的UITableViewCell类上使用委托:

UIView

这里还有UITableViewCell上的相应代码

import UIKit
public protocol CustomCellDelegate: class {

func customButtonClick()

}

class CustomTableViewCell: UITableViewCell {


    @IBOutlet weak var customButton: UIButton!

    weak var delegate: CustomCellDelegate?


    @IBAction func customButtonAction(_ sender: UIButton) {
    
      delegate?.customButtonClick()

    } 
  .. }

我知道MainViewController在两个不同的控制器(import UIKit class MainViewController: UIViewController,CustomCellDelegate { @IBOutlet var UIViewButton: UIView! func customButtonClick() { self.UIViewButton.frame = CGRect (x:20,y: 300,width: 369,height: 46) self.view.addSubview(UIViewButton) } } CustomTableViewCell)中,因此我认为其中一个可能存在委托问题/我可能需要添加这些控制器的另一个代表,但我不确定如何。我设法更改了CustomTableView中的CustomTableViewController图标,所以我知道它是可点击的,但似乎无法让它委托customButton或与之通信并拥有{ {1}}出现。很抱歉给您带来的困惑和不便,在此方面的任何帮助将非常感激,因为我是编码的初学者。非常感谢!! ^ __ ^

更新:

CustomTableViewCell

MainViewController

UIViewButton

CustomTableViewController:

解决方法

我希望您的UI与下图类似。

enter image description here

为此,我将执行以下操作

  1. 声明一个协议,该协议将让您知道何时显示或隐藏“发送”按钮。 例如

     protocol ContactListTableViewControllerDelegate: class {
         func showSendButton() 
         func hideSendButton()
     }
    
  2. 使第一个视图控制器成为表视图控制器类的委托

  3. 您已经创建了一个协议,用于拾取单元格内按钮上的点击事件。 (可选)您还需要添加该单元格作为参数,以便委托人知道单击了哪个单元格。

     public protocol CustomCellDelegate: class {
    
         func customButtonClick(cell: CustomTableViewCell)
    
     }
    
  4. 在cellForRowAtIndexPath方法中创建每个单元格时,使表视图控制器成为该单元格的委托

     cell.delegate = self
    
  5. 在表视图控制器子类中实现委托方法

     func customButtonClick(cell: CustomTableViewCell) {
         // Find the index path for the clicked cell
         // You should have an array for storing the indices of selected cells
         // Check if the index is already in the array. If yes,remove it from 
         //the array (deselection)
         // If no,add the index to the array(selection)
         // Check the count of the array
         // If it is > 0,it means at least one cell is selected. Call the 
         // delegate method
         // to show button
         delegate?.showSendButton()
         // Else call delegate method to hide send button
         delegate?.hideSendButton()
     }