最近,我正在尝试做一些练手项目。因此,我观看了斯坦福大学2017年CS193P课程“为iOS开发应用程序”。
现在,我正在做“Smashtag”项目,但我遇到了一些问题。我想使用CollectionView和两个UICollectionViewFlowLayout,在每个xib中显示两种类型(一种类似于tableView,另一种显示正方形的图像),通过SegmentedControl在CollectionView中显示。
我的问题如下:
如何使CollectionViewCell像TableView的UITableViewAutomaticDimension一样以动态高度显示?
这是我刚刚尝试过的:
我尝试使用UICollectionViewFlowLayoutAutomaticSize(@available(iOS 10.0, *))将CollectionView的autoResize设置成与TableView的autoDimension相同。
enum CollectionViewType {
case tweet
case image
}
// MARK: - Decide What Kind Of FlowLayout
func decideFlowLayout(type: CollectionViewType) -> UICollectionViewFlowLayout {
// just for .image type
var howManyImageShowing = 3
var imageShowingWidth: Double {
return Double(self.view.frame.width) / Double(howManyImageShowing)
}
// .tweet is a type showing like TableViewCell -> this make me confused !!
// another type is just showing a image in square -> I have no problem here
let estimatedItemSize = type == .tweet ? CGSize(width: self.view.frame.width, height: 155.0) :
CGSize(width: imageShowingWidth, height: imageShowingWidth)
let collectionViewLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
collectionViewLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
// --------- Make this setting as TableView does ---------
// ------------ Somethis just like this below ------------
/*
tableView.estimatedRowHeight = 155.0
tableView.rowHeight = UITableViewAutomaticDimension
*/
collectionViewLayout.estimatedItemSize = estimatedItemSize
collectionViewLayout.itemSize = UICollectionViewFlowLayoutAutomaticSize
// -------------------------------------------------------
collectionViewLayout.minimumLineSpacing = 0
collectionViewLayout.minimumInteritemSpacing = 0
return collectionViewLayout
}
我的CollectionViewCell的Xib文件有问题:
但是我运行应用程序时出现了错误。
我不知道我错过了什么或者我误解了什么。
为什么这个解决方案会起作用?
我在Stack Overflow上搜索了很多关于这个问题的解决方案,但我只找到了这个并且让我非常困惑:(
这个解决方案给视图一个宽度约束(在CollectionViewCell xib中),并设置这个约束的常量值,它就能正常工作了! 我无法理解为什么宽度约束会使单元格的高度动态变化? 这真的让我感到困惑,我认为这很奇怪...
class Cell: UICollectionViewCell {
@IBOutlet weak var headerLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var widthConstraint: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.contentView.translatesAutoresizingMaskIntoConstraints = false
let screenWidth = UIScreen.main.bounds.size.width
widthConstraint.constant = screenWidth - (2 * 12)
}
}
如何在不使用 UICollectionViewFlowLayoutAutomaticSize. ( @available(iOS 10.0, *) )的情况下实现CollectionViewCell的动态高度?
因为我想要处理不仅在iOS 10中而且在iOS 10以下的不同iOS版本。
我真的想成为iOS开发专家和优秀的开发人员,但我还在学习和尝试。非常感谢任何回复。
谢谢!!