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

时间:2019-02-20 19:45:38

标签: swift uicollectionview uicollectionviewcell frame uicollectionviewlayout

我有一个自定义UICollectionViewCell,其中有一个UIImage和一个UIButton

扩展单元格的帧为110 x60。默认情况下为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,然后为按钮的动作创建委托。

1 个答案:

答案 0 :(得分: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)

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