iOS Swift开发之日历插件开发示例

2020-01-21 00:41:19王冬梅


extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
  // 返回Section的数量
  func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 0
  }
  // 返回Item的数量
  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 0
  }
  // 返回Cell
  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "dateItem", for: indexPath) as! dateCollectionViewCell
    return cell
  } 
}

这三个函数是必须写上的,numberOfSections返回Section的数量,numberOfItemInSection返回Section中Item的数量,cellForItemAt返回一个cell

最需要注意的是,在ViewController中的viewDidLoad函数中,必须添加如下


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    // 这两句话很重要!!!
    CalendarCollectionView.dataSource = self
    CalendarCollectionView.delegate = self
  }

这里我们设置两个Section,第一个存放“一二三四五六日”,第二个存放日期

那么Item数量就要分类考虑,Section为1时为7,Section为2时呢?为了简化,我们就return 42个。

那么cell也需要分类考虑


extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
  // 返回Section的数量
  func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 2
  }
  // 返回Item的数量
  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if section == 0 {
      return weekArray.count
    } else {
      return 42
    }
  }
  // 返回Cell
  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "dateItem", for: indexPath) as! dateCollectionViewCell
    if indexPath.section == 0 {
      cell.textLabel.text = weekArray[indexPath.row]
    } else {
      var daysArray: [String] = []
      // 第一天之前的空白区域
      for number in 0..<firstDayOfMonth-1 {
        daysArray.append("")
      }
      for number in firstDayOfMonth-1...firstDayOfMonth+numberOfTheMonth-2 {
        daysArray.append(String(number-firstDayOfMonth+2))
      }
      // 最后一天后的空白区域
      for number in firstDayOfMonth+numberOfTheMonth-2...41 {
        daysArray.append("")
      }
      cell.textLabel.text = daysArray[indexPath.row]
    }
    return cell
  }
}

显示上个月和下个月只需在按钮的Action中month-1,再判断一下month是否在1...12范围内。以上一个月为例