【问题标题】:How to change frame of UICollectionViewCell to reveal hidden button on tap?如何更改 UICollectionViewCell 的框架以在点击时显示隐藏按钮?
【发布时间】:2019-02-20 19:45:38
【问题描述】:

我有一个自定义的UICollectionViewCell,它有一个UIImage 和一个UIButton

扩展单元格的边框为 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,然后为按钮的操作创建一个委托。

【问题讨论】:

  • 发布你的 UICollectionViewCell 类代码
  • 为单元格中的imageView设置恒定宽度并删除按钮的尾随或右约束,同时设置按钮的宽度。

标签: swift uicollectionview uicollectionviewcell frame uicollectionviewlayout


【解决方案1】:

我认为很大程度上取决于您在 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)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多