Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. import UIKit
  2.  
  3. class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
  4.  
  5.  
  6. @IBOutlet weak var collectionView: UICollectionView!
  7. @IBOutlet weak var label: UILabel!
  8.  
  9. let now = Date()
  10. var cal = Calendar.current
  11. let dateFormatter = DateFormatter()
  12. var components = DateComponents()
  13.  
  14. override func viewDidLoad() {
  15. super.viewDidLoad()
  16.  
  17. cal.locale = Locale(identifier: "ja")
  18. dateFormatter.locale = Locale(identifier: "ja_JP")
  19. dateFormatter.dateFormat = "yyyy年M月"
  20. components.year = cal.component(.year, from: now)
  21. components.month = cal.component(.month, from: now)
  22. components.day = 1
  23. calculation()
  24. }
  25.  
  26. func calculation(){
  27. let firstDayOfMonth = cal.date(from: components)
  28. label.text = dateFormatter.string(from: firstDayOfMonth!)
  29. }
  30.  
  31. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  32. return 37
  33. }
  34.  
  35. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  36. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
  37. let firstDayOfMonth = cal.date(from: components)
  38. let firstWeekday = cal.component(.weekday, from: firstDayOfMonth!)
  39.  
  40. let weekdayAdding = 2 - firstWeekday
  41. for subview in cell.contentView.subviews {
  42. subview.removeFromSuperview()
  43. }
  44.  
  45. let daysCountInMonth = cal.range(of: .day, in: .month, for: firstDayOfMonth!)?.count
  46. if (indexPath.row + weekdayAdding) >= 1 && (indexPath.row + weekdayAdding) <= daysCountInMonth! {
  47. cell.backgroundColor = #colorLiteral(red: 0.937254902, green: 0.937254902, blue: 0.9568627451, alpha: 1)
  48. let label = UILabel()
  49. label.font = UIFont(name: "Arial", size: 17)
  50. label.text = "\(indexPath.row + weekdayAdding)"
  51. label.sizeToFit()
  52. label.center = cell.contentView.center
  53. cell.contentView.addSubview(label)
  54. }
  55. else{
  56. cell.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
  57. }
  58. return cell
  59. }
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement