【问题标题】:How to create outlet from collection cell xib file to collection view controller如何创建从集合单元 xib 文件到集合视图控制器的出口
【发布时间】:2018-03-09 17:35:52
【问题描述】:

我有自定义的 Collection View Cell 和 .swift 和 .xib 文件。在 .xib 文件中,我有 textField ,我必须从 Collection ViewController 中获取数据并采取相应措施,但我不确定如何,因为 .xib 文件具有 Collection View Cell 的自定义类,我 无法为Collection ViewController 文件创建 出口,因此我可以参考它。

如果我在 Collection View Cell 中创建一个出口,我无法在 Collection ViewController 中引用它。

【问题讨论】:

标签: ios swift uicollectionview xib


【解决方案1】:

你不能那样做。 您不能创建引用放置在 CollectionViewController 中的自定义 CollectionViewCell 内的 UITextField 的插座。

您可以做的是创建一个插座,在相应的 CollectionViewCell .swift 类 (1) 中引用您的 .xib 中的 UITextField,在 CollectionViewController (2) 中创建一个引用您的 collectionView 的插座,然后使用这些 CollectionViewCells 在你的 collectionView (3)。

然后,您可以通过单元格本身 (3) 访问 CollectionViewController 中特定 CollectionViewCell 的 UITextField,例如:

let indexPath = IndexPath(row: 2, section: 0)
let cell = self.collectionView.cellForItemAtIndexPath(indexPath) as! CollectionViewCell // so the compiler knows that the cell you are referring to is of type CollectionViewCell and thus has your custom textField property

let textInTextField = cell.textField.text

(1)

(2)

(3)

【讨论】:

  • 非常感谢我解决了这个问题。你知道为什么当从 textField 显示键盘时,单元格会向上移动并留下空白...
  • @Viktor ?。不太清楚,当键盘出现时,你是如何管理视图的?
  • 没什么特别的,我在 textFieldShouldReturn() 中只有 textField.resignFirstResponder() 。这是我打开键盘之前的单元格正确布局 - i.stack.imgur.com/AgCyX.png,这是在我显示键盘之后 - i.stack.imgur.com/Nnl43.png
  • 如果您使用的是 UICollectionViewController,也许它嵌入了在键盘出现时移动视图的逻辑。在这种情况下,您可以尝试使用带有委托和数据源的普通 UIViewController,如 i.stack.imgur.com/IEcbN.jpgi.stack.imgur.com/aS6Gg.jpg 中的,以查看行为是否发生变化。但我不确定。
  • 当这出现时,如果我进入下一个单元格,我将单元格再次向上移动,因此所有单元格都会发生这种情况......
【解决方案2】:

据我所知,您需要一种从 CollectionViewCell 访问 CollectionViewController 数据的方法,如果是这种情况,您可以尝试以下方法:

extension UIView {
    var parentViewController: UIViewController? {
        var parentResponder: UIResponder? = self
        while parentResponder != nil {
            parentResponder = parentResponder!.next
            if let viewController = parentResponder as? UIViewController {
                return viewController
            }
        }
        return nil
    }
}

//In the CollectionViewCell class
if let controller = self.parentViewController as? YourViewController
{
    controller.action()
}

通过此扩展,您可以访问单元的父控制器并根据需要执行功能或获取数据

一个例子: https://github.com/AngelH2/CollectionViewCell-Comunication/tree/master/CollectionCellAction

【讨论】:

  • 感谢您的帮助,我尝试添加扩展名并将此代码添加到我的单元格中,但编译器根本没有进入 if 语句,我可以运行模拟器...:如果让控制器 = self.parentViewController 作为? CollectionOneController { print(controller.simpleAction()) }
  • 该函数是否返回任何要打印的值?就我而言,我为图像查看器添加了该功能,其中我有 2 个按钮可以在 CollectionViewCell 中向左和向右移动,因为我需要某种方法来从单元格中执行父控制器中的函数才能做一个滚动,我用了那个功能,结果很好
  • 如果代码不起作用,请尝试以下操作:在单元格中添加一个按钮并对其进行编程,以便在按下它时调用主控制器功能
  • 我怎么做才能在按下时调用主控制器功能?你能用一些代码更新问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
相关资源
最近更新 更多