【问题标题】:How to access an instance of UIStackView inside a cell in swift?如何快速访问单元格内的 UIStackView 实例?
【发布时间】:2019-05-18 03:48:44
【问题描述】:

我有一个stackView(称为'btnStack'),它在一个单元格(类'PresentationCell')中保存四个按钮,我试图用以下代码隐藏它:

func hideBtnStack() {
    let cell = collectionView.visibleCells.first as! PresentationCell

    cell.btnStack.isHidden = true

}

但是,当我运行代码时,出现以下错误:

'线程 1:致命错误:在展开可选值时意外发现 nil'

是否有更简单/更好的方式来访问单元格中的 btnStack?

cellForRowAt中的相关代码为:

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! PresentationCell

 }

我还在 PresentationCell 类中声明了 btnStack,如下所示:

class PresentationCell: UICollectionViewCell {

@IBOutlet weak var textView: UITextView!

@IBOutlet weak var btnStack: UIStackView!

}

而我首先在ViewDidLoad中调用hideBtnStack方法如下:

override func viewDidLoad() {
    super.viewDidLoad()


    collectionView.dataSource = self
    collectionView.delegate = self

    setUpCollectionView()

    hideNavBar()

    hideBtnStack()


}

提前感谢您提供的任何帮助。

【问题讨论】:

  • 你确定第一个可见单元格是PresentationCell吗?你能分享你的cellForRowAt 代码吗?
  • 你有多少种细胞?
  • 感谢您的快速回复。现在已经在上面添加了 CellforRowAt 代码。在这个presentationViewController 中只有一种单元格,即PresentationCell。
  • 一种可能是你在collection view有任何数据之前调用hideBtnStack,你也可以分享你设置数据源的位置和你调用hideBtnStack的位置吗?
  • 谢谢。我最初认为这也可能是一个问题。但我确保在 setUpCollectionView 以及 viewDidLoad 中的相关委托和数据源方法之后声明了 hideBtnStack。

标签: swift uicollectionviewcell stackview


【解决方案1】:

CjCoax 给了我如何解决这个问题的线索。看起来如果在 viewDidLoad 中声明了 hideBtnStack 以及它在可以填充 collectionView 之前执行的 collectionView 方法。我通过延迟 hideBtnStack 方法解决了这个问题,现在它可以工作了。

override func viewDidLoad() {
    super.viewDidLoad()

    collectionView.dataSource = self
    collectionView.delegate = self


    setUpCollectionView()

    hideNavBar()

    DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
        self.hideBtnStack()
    }


}

【讨论】:

  • 这不是办法!如果默认情况下必须隐藏堆栈视图,为什么不直接在单元类中进行呢?
  • 感谢您的建议。让我试试看。
【解决方案2】:

我认为这个解决方案可能会对您有所帮助!试试这个。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? PresentationCell else { return UICollectionViewCell() }

if indexPath.item == 0 { 
    // hide your view
    cell.btnStack.isHidden = true
}

}

注意:尽量避免来自force unwrapping。

我希望这个解决方案对你有用。

【讨论】:

  • 感谢此代码和 Rakesha 的回复。尽管我在单独的函数“hideBtnStk”中编写代码的原因是我希望能够隐藏和取消隐藏(即切换)UIStackView 的外观。我现在知道(我认为)原始函数不起作用的原因是它是在设置 collectionView 之后在 viewDidLoad 中调用的。所以, hideBtnStack 确实有效。但现在的问题是,它只隐藏和取消隐藏可见单元格的按钮,而不是滚动到之后(或之前)的按钮。
  • 所以,现在我正在寻找一种方法来遍历 collectionView 中的所有单元格,以便我可以一致地在 btnStack 上设置“isHidden”状态。
猜你喜欢
  • 1970-01-01
  • 2015-07-06
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多