将 UIButton 设置为 UICollectionViewCell 的大小

Set a UIButton to the size of a UICollectionViewCell

我为 UICollectionViewCell 定制了一个名为 ChronicleCell 的 class。

我正在创建 UIButton 类型的实例变量。

 class ChronicleCell : UICollectionViewCell {
    //init etc.
    var buttonFullCellSize : UIButton = {
       let button = UIButton()
        //TODO set button to be size of UICollectionViewCell frame

    }()

 }

对于这个实例变量,我想将它的框架设置为等同于UICollectionViewCell的框架。然而,这在继承自 UICollectionViewCell 的 class 中是不可访问的。我怎样才能做到这一点?谢谢!

将 collectionViewLayout 的框架分配给按钮的框架:

let rect = self.collectionViewLayout.layoutAttributesForItemAtIndexPath(clIndexPath).frame
button.frame = button.rect

您的代码可能是:

 class ChronicleCell : UICollectionViewCell {
    //init etc.
    var buttonFullCellSize : UIButton = {
       let button = UIButton()
       let frameOfUICollectionViewCell = self.collectionViewLayout.layoutAttributesForItemAtIndexPath(clIndexPath).frame
       button.frame = button.rect
       return button
    }()

 }

单元格的 contentView 与单元格大小相同,因此您应该使用它来获取框架。

var buttonFullCellSize: UIButton {
    let button = UIButton()
    button.frame = contentView.frame
    return button
}