我正试图建立一个时间线。我有一个包含collectionView的视图控制器。每个collectionView单元格代表一个月的数据。在每个单元里我都有一个stackView。这个stackView包含30个子视图,每个子视图代表一天的数据。
如果你想试试,完整的项目就在这里:https://github.com/AlexMarshall12/iOS-timeline
我当前为每个dayCell子视图着色的方法是在自定义单元格的awakeFromNib中创建单元格中的所有子视图。
class MonthCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var stackView: UIStackView!
var dayViews: [Int:UIView] = [:]
override func awakeFromNib() {
super.awakeFromNib()
for i in 1...30 {
let tick = UIView()
dayViews[i] = tick
self.stackView?.addArrangedSubview(tick)
}
}
}
注意,我还构建了一个字典,为单元格中的每个子视图从1到30建立索引。
然后在我的viewController中,在collectionView的cellfortitemat方法中,我使用“dates”函数查看当月数据中的日期。然后我用之前构建的字典查找这个视图,并将其涂成红色。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MonthCollectionViewCell", for: indexPath) as! MonthCollectionViewCell
cell.backgroundColor = UIColor.gray
let dayViews = cell.dayViews
let firstDate = dates.first
let index = indexPath.item
let monthDate = Calendar.current.date(byAdding: .month, value: index, to: firstDate as! Date)
let monthInt = Calendar.current.component(.month, from: monthDate!)
let yearInt = Calendar.current.component(.year, from: monthDate!)
let monthDates = dates(self.dates as! [Date], withinMonth: monthInt, withinYear: yearInt)
for date in monthDates {
let dayInt = date.interval(ofComponent: .day, fromDate: (monthDate?.startOfMonth())!)
let tick = dayViews[dayInt]
print(tick,"tick")
tick?.backgroundColor = UIColor.red
}
return cell
}
func dates(_ dates: [Date], withinMonth month: Int, withinYear year: Int) -> [Date] {
let calendar = Calendar.current
let components: Set<Calendar.Component> = [.month,.year]
print(components,"components")
let filtered = dates.filter { (date) -> Bool in
let monthAndYear = calendar.dateComponents(components, from: date)
return (monthAndYear.month == month && monthAndYear.year == year)
}
return filtered
}
目前,所有内容都显示为灰色的月份单元格,可以从右向左滚动。尽管我的控制台告诉我它的发现与颜色匹配,但它似乎没有给它们上色。我在这个方法/实现中做错了什么?
最佳答案
当你遇到“我没有看到我期望看到的视图”的情况时,在模拟器中运行你的应用程序,然后在Xcode中启动视图调试器。
在这种情况下,当您这样做时,您将立即看到您的错误:您的所有“ticks”都是不可见的,因为您将零大小的普通uiview作为排列的子视图发送到“Fill distribution”堆栈视图。堆栈视图不知道这些是怎么回事。所以它们最终没有大小,这使得它们看不见。
在XIB编辑器中更改“填充分布”到“填充均匀分布”,再次运行应用程序,然后,您将开始看到一些蜱!
关于ios - 如何在collectionView单元格的cellForItemAt中为 subview 着色?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50915834/