如何更改UICollectionViewCell的框架以显示隐藏的按钮?

问题描述 投票:0回答:1

我有一个定制的UICollectionViewCellUIImageUIButton

扩展单元的帧为110 x 60.默认情况下为60x60。

当应用程序加载时,我希望单元格以60x60开始并仅显示图像。当点击单元格时,单元格将更新为110x60帧并显示图像旁边的UIButton。

目前,我的应用程序确实加载,单元格为60x60,但由于我的自动布局设置,图像被压扁,按钮是全尺寸。如果我点击单元格,它会更新它的框架,它看起来很棒。

目标是仅先查看图像,然后在单元格更新其框架后再查看按钮。

我还希望能够再次点击单元格并将其重新调整为60x60,隐藏按钮并仅显示图像。

这是我目前正在尝试的:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    collectionView.performBatchUpdates(nil, completion: nil)
}

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAt indexPath: IndexPath) -> CGSize {

    switch collectionView.indexPathsForSelectedItems?.first {
    case .some(indexPath):
        return CGSize(width: 110.0, height: 60.0)
    default:
        return CGSize(width: 60.0, height: 60.0)
    }

}

每个请求,我的CollectionViewCell类代码:

class myCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var myImageView: UIImageView!
    @IBOutlet weak var myButton: UIButton!

    var myCellDelegate : myCollectionViewCellDelegate?

    override func awakeFromNib() {
        super.awakeFromNib()

        self.layer.cornerRadius = 30
        self.layer.masksToBounds = true

        myImageView.layer.cornerRadius = myImageView.frame.width / 2
        myImageView.layer.masksToBounds = true
    }

    // MARK: - Actions

    @IBAction func myButtonTapped(_ sender: Any) {
        self.myCellDelegate?.actionClicked(self)
    }
}

要注意的是,那里没有那么多,所以不确定它是否会有所帮助。我只是调整单元格和我的图像的cornerRadius,然后为按钮的动作创建一个委托。

swift uicollectionview uicollectionviewcell frame uicollectionviewlayout
1个回答
0
投票

我认为很大程度上取决于你在nib文件中的约束。

选项1

界面构建器>选择您的ImageView>右侧面板>大小检查器>使用“内容拥抱优先级”和“内容压缩阻力”进行播放

特别是imageView的水平抗压性必须大于按钮的抗压性。

系统根据为这两个参数指示的优先级选择要拉伸的视图。

选项2


            Top                   
     +-------------+--------+     
     |             |        |     
     |             |        |     
 Left|   (Image)   |(Button)|Right
     |             |        |     
     |             |        |     
     +-------------+--------+     
          Bottom                  

     <------------->              
          Width               

Left, Top, Right, Bottom ---> constraint to the cell contentView
Width ---> set to a fixed 60
(Remember to enable clipsToBounds)

当单元格放大时,将出现按钮。您最终可以添加动画。

© www.soinside.com 2019 - 2024. All rights reserved.