ios - 尝试确定子类 UICollectionViewCell 中的单元格宽度

标签 ios swift uicollectionview uicollectionviewcell

我有一个基本的子类 UICollectionView Cell。我想向其中添加一个 UIImageView,以便每个单元格都显示一个图像。

如果我向 x:y:width:height 添加显式值,图像会正确显示,但我无法使用 self.contentView.frame.width 来确定 Collection View 的大小单元格(用于将图像放置在 x 轴上)

class SubclassedCell: UICollectionViewCell {
    var myImageView: UIImageView!
    required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
        myImageView = UIImageView(frame: CGRect(x: (self.frame.width - 10.0), y: 50.0, width: 20.0, height: 20.0))
        myImageView.image = UIImage(named: "JustinBieber")
        self.contentView.addSubview(myImageView)
    }
}

在上面,(self.contentView.frame.width - 10.0) 没有获取 Collection View 单元格的大小,所以图像根本不显示。如果我明确地为 x 输入一个值,比如说 0,它就会显示出来。

如何确定子类 Collection View 单元格的大小(宽度)?

最佳答案

在 View 生命周期的早期调用初始化程序以准确地提供维度值。

更惯用的方法是在 layoutSubviews 生命周期方法中布置图像。一个简单的例子如下所示

class SubclassedCell: UICollectionViewCell {

    var myImageView: UIImageView!
    var imageDisplayed = false

    override func layoutSubviews() {
        super.layoutSubviews()
        if !imageDisplayed {
            myImageView = UIImageView(frame: CGRect(x: (self.frame.width - 10.0), y: 50.0, width: 20.0, height: 20.0))
            myImageView.image = UIImage(named: "JustinBieber")
            self.contentView.addSubview(myImageView)
            imageDisplayed = true
        }
    }
}

如果您在应用程序中使用自动布局,您可能还需要考虑添加图像并提供约束,而不是显式设置图像的框架。

如图所示 answer - 根据您的用例 - 它们可能是设置手机的更好方法。

关于ios - 尝试确定子类 UICollectionViewCell 中的单元格宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43334702/

相关文章:

ios - iPad SplitViewController leftViewController 是 UITableViewController 和返回按钮从上到下重绘屏幕

ios - 访问 ABAddressBook 时出错

ios - 请求错误代码为 999 的 AFNetworking

ios - 如何在 Swift 5.0/Xcode 中使用🧨 强制解包

ios - 横向更改 UISplitViewController 的 UITableViewController Master 的背景图像

ios - 水平自动滚动 UICollectionviewcell

ios - 如何在 CollectionView 中添加页脚/页眉

ios - 在用帧 0,0,0,0 初始化的 Storyboard 中创建的 ScrollView

string - Swift - 可选字符串与隐式解包可选字符串

ios - 简单动画问题 Xcode 7 Swift