【问题标题】:Show image in selectItemAtIndexPath with Swift使用 Swift 在 selectItemAtIndexPath 中显示图像
【发布时间】:2014-10-29 12:36:34
【问题描述】:

我有collectionView,每个单元格中都有图像。 我想在点击单元格时查看完整图像。

我知道这可以通过 selectItemAtIndexPath 方法完成,并且我需要对选定的单元格做一些事情:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
   println("Row: \(indexPath.row) is selected")

   var cell:UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
}

我在 objc 中看到了很多代码示例,例如 here,但我在 Swift 中无法弄清楚。

提前谢谢你


更新:

到目前为止我的代码:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{   
    collectionView.collectionViewLayout.invalidateLayout()
    let cell = collectionView.cellForItemAtIndexPath(indexPath)
    let animateChangeWidth = { [weak cell] in
        let frame:CGRect = cell.frame
        frame.size = cell.intrinsicContentSize()
        cell.frame = frame
    }
    UIView.transitionWithView(cell, duration: 0.7, options: UIViewAnimationOptions.CurveLinear, animations: animateChangeWidth, completion: nil)
}

我得到的错误是在块行的开头:

Cannot convert the expression's type '() -> () -> $T0' to type '() -> () -> $T0'

我认为它仍然与定义(弱)单元格有关。

【问题讨论】:

    标签: swift uiimageview uicollectionview


    【解决方案1】:

    与您链接的帖子类似,使布局无效,然后设置一个称为动画块的闭包。

    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
    {
        collectionView.collectionViewLayout.invalidateLayout()
        let cell = collectionView.cellForItemAtIndexPath(indexPath)!
        let animateChangeWidth: ()-> Void  = {[weak cell] in
            if let validCell = cell {
                var frame = validCell.frame
                frame.size = validCell.viewWithTag(100)!.intrinsicContentSize()
                validCell.frame = frame
            }
    
        }
        UIView.transitionWithView(cell, duration: 0.7, options: UIViewAnimationOptions.CurveLinear, animations: animateChangeWidth, completion: nil)
    }
    

    【讨论】:

    • 感谢您的快速反应,我只是不明白您对weak cell 的意思是什么?你还在闭包中使用;吗?
    • [weak cell] 是一个闭包 Capture List 以避免保留循环。我把它放在那里是因为另一个人使用了对cell 的弱引用,所以我想我们最好也在这里使用它。 (删掉分号,不需要,复制粘贴出错)
    • 仍然无法工作@JMFR。它给了我一个奇怪的错误,告诉我它无法转换表达式的类型。见更新。似乎这个问题超出了我的范围
    • 目前没有 Xcode。您可以尝试离开捕获列表。删除[weak cell] in 部分?或者为我们的闭包声明一个类型,应该是() -> Void
    • 我确实让代码工作并触发动画,但我也不是集合视图专家。您可以在https://github.com/regnerjr/CollectionViewTest 处查看代码,这是一个简单的集合视图,其中包含在选择时缩放的图像。问题是当所选图像缩放时,集合中的其他视图不会移开。如果您需要更多帮助,请随时与我们联系。
    猜你喜欢
    • 2018-09-04
    • 2016-06-12
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 2016-06-15
    相关资源
    最近更新 更多