【发布时间】:2017-12-25 12:50:51
【问题描述】:
最近,我正在尝试做一些练习项目。于是,我观看了斯坦福大学 CS193P,2017 年的课程“Developing Apps for iOS”。
现在,我正在做“Smashtag”项目,但我遇到了一些问题。 我想使用带有两个 UICollectionViewFlowLayout 的 CollectionView 通过 SegmentedControl 在 CollectionView 的每个 xib 中显示两种类型(一种类似于 tableView,另一种以正方形显示图像)。
我的问题如下:
如何让 CollectionViewCell 像 TableView 的 UITableViewAutomaticDimension 一样以动态高度显示?
这就是我刚刚在下面尝试过的:
我尝试使用 UICollectionViewFlowLayoutAutomaticSize 使 CollectionView 的 autoResize 设置与 TableView 的 autoDimension 一样。 (@available(iOS 10.0, *))
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 中搜索了很多这个问题的解决方案,但我发现这个让我很困惑:(
此解决方案为视图提供了一个 Width Constraint,它位于 CollectionViewCell xib 中,并将此约束的常量设置为一个值,它就可以工作了!我无法配置为什么 Width Constraint 会使单元格的高度动态变化?这让我很困惑,我觉得这很奇怪......
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 的情况下做 CollectionViewCell 动态高度。 (@available(iOS 10.0, *)) ?
因为我想处理不同的 iOS 版本,不仅在 iOS 10 中,而且在 iOS 10 以下。
我真的很想成为 iOS 开发方面的专业人士和优秀的开发人员,但我仍在学习和尝试。任何答复我将不胜感激。
谢谢!!
【问题讨论】:
标签: ios dynamic swift3 uicollectionview autolayout