1080p 高清视频的纵横比为 16:9,并为单元格中的视频设置帧,以便将其完全填满,我会使用 view.frame.width * 9 / 16
:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// the collection view is pinned to both sides of the vc with no spacing
let width = collectionView.frame.width
let videoHeight: CGFloat = width * 9 / 16
return CGSize(width: width, height: videoHeight)
}
// inside the cell itself:
let videoHeight: CGFloat = self.frame.width * 9 / 16
contentView.addSubview(thumbnailImageView)
thumbnailImageView.topAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
thumbnailImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
thumbnailImageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
// here is where I set the thumbnail's height
thumbnailImageView.heightAnchor.constraint(equalToConstant: videoHeight).isActive = true
这完美地给了我:
问题是我想要一个类似于 youtube 的较小版本的 thumbnailImageView。我想在屏幕左侧添加较小的 thumbnailImageView 但保持纵横比相同。
问题是当我尝试这样做时,我得到了一个正方形而不是一个矩形。我将单元格的宽度除以 3,然后将其乘以 9 /16,但这不起作用。我之所以使用(width / 3)
它是因为我虽然它会保持纵横比不变,但会减小 thumbnailImageView 的大小,但它不起作用。
我哪里错了?
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// the collection view is pinned to both sides of the vc with no spacing
let width = collectionView.frame.width
let videoHeight: CGFloat = (width / 3) * 9 / 16
return CGSize(width: width, height: videoHeight)
}
// inside the cell itself
let videoHeight = (self.frame.width / 3) * 9 / 16
contentView.addSubview(thumbnailImageView)
thumbnailImageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8).isActive = true
thumbnailImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8).isActive = true
// here is where I set the thumbnail's height and width
thumbnailImageView.heightAnchor.constraint(equalToConstant: videoHeight).isActive = true
thumbnailImageView.widthAnchor.constraint(equalToConstant: videoHeight).isActive = true