【发布时间】:2020-08-19 14:08:28
【问题描述】:
我正在 Xcode/Swift 中开发一个 iOS 应用程序,当在单独的 UITableViewController 中单击 UITableViewCell 按钮时,我试图在我的 MainViewController 中添加一个子视图 UISendViewButton(它本身就是嵌入UIView)。基本上,这个概念类似于 Instagram 中的“发送帖子”按钮:用户将单击纸飞机按钮,然后出现一个单独的朋友列表(UIView -> UITableViewController)。在联系人列表旁边,有一个按钮 (customButton),用户可以单击该按钮来选择将其发送给哪些朋友。我想要的是只有当用户决定点击他们朋友名字旁边的按钮 (customButton) 时才会出现“发送”按钮 (UIViewButton)。
我能够通过将UITableViewController 嵌入到UIView 中,然后将其作为子视图添加到我的MainViewController 中来显示它,但是当我单击UITableViewCell 类中的customButton 时,什么也没有发生。我希望在单击customButton 时出现一个新的UIViewButton(在我的MainViewController 中)。
所以基本上我想知道如何让这两个控制器进行通信。包含 UITableViewCell 按钮的控制器是 Xcode 库提供的控制器:UITableViewController -> UITableView -> 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),所以我认为其中一个控制器中可能存在委托问题/我可能需要为这些控制器添加另一个委托,但是我不确定如何。我设法更改了CustomTableViewCell 中的customButton 图标,所以我知道它是可点击的,但我似乎无法让它代表MainViewController 或与MainViewController 通信并让UIViewButton 出现。对于给您带来的困惑和不便,我深表歉意,由于我是编码初学者,因此将不胜感激。非常感谢!! ^__^
更新:
CustomTableViewController:
public protocol ContactListTableViewControllerDelegate: class {
func showSendButton() }
class CustomTableViewController: UITableViewController, CustomCellDelegate {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "likesCell", for: indexPath) as! CustomTableViewCell
cell.delegate = self }
func customButtonClick() {
delegate?.showSendButton()
} }
MainViewController:
extension MainViewController: ContactListTableViewControllerDelegate {
func showSendButton() {
self.UISendButton.frame = CGRect (x:20, y: 300, width: 369, height: 46)
self.view.addSubview(UISendButton)
} }
【问题讨论】:
-
如何将主控制器连接到单元格的委托变量?
-
@PhillipMills 非常感谢您的回复!我将 CustomCellDelegate 放在 MainViewController 的类中,所以它看起来像这样:“class MainViewController: UIViewController, CustomCellDelegate {”是你的意思吗?
-
不,这只是声明您的 MainViewController 能够成为 CustomCellDelegate。需要做的是告诉每个单元格它的
delegate变量应该指向什么对象。
标签: ios swift xcode uitableview delegates