我正在使用集合视图设计日历。我每个月都会得到一周的日子。如果对于01-02-207星期几从3开始,我需要从集合视图的第3个位置加载单元格。如果我得到6,我应该从第6位加载。任何人都可以帮忙吗?
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let s = CGSize(width: CGFloat(UIScreen.main.bounds.size.width / 7), height: CGFloat(UIScreen.main.bounds.size.height / 7))
return s
}
//UICollectionViewDatasource methods
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numDays
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier,for:indexPath) as! collectDayCellCollectionViewCell
let myString = String(yourArray[indexPath.row])
cell.day_lbl.text = myString
cell.backgroundColor = self.randomColor()
return cell
}
// custom function to generate a random UIColor
func randomColor() -> UIColor{
let red = CGFloat(drand48())
let green = CGFloat(drand48())
let blue = CGFloat(drand48())
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
答案 0 :(得分:1)
您可以使用结构来保存每个日历月所需的所有信息。我不知道你从哪里获取你的数据,对某些API的查询或者你在某个地方有一个数组,但下面应该让你去。请注意,这可能是更好的解决方法。
import UIKit
struct MonthStruct {
var monthSequence: Int // this will help sort the array
var month : String
var numberOfDays : Int
var startIndex : Int // or startDay if using days
}
class MyClass: UIViewController {
// make an array from the struct items
var monthArray = [MonthStruct]()
override func viewDidLoad() {
for months in year { // year being your data source from query or array????
// hardcoding values to demonstrate
monthArray.append(MonthStruct(monthSequence: 1, // : month[0] // : month.object.objectForKey.....
month: "Janruary", // : month[1]
numberOfDays: 31, // : month[2]
startIndex: 3) // : month[3]
)
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// [0] or other depending on month you want to display
return monthArray[0].numberOfDays
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier,for:indexPath) as! collectDayCellCollectionViewCell
// this will just show stuff for cells after Tuesday
if indexPath.item >= monthArray[0].startIndex {
cell.day_lbl.text = myString
cell.backgroundColor = self.randomColor()
}
return cell
}
}