制作日历步骤

1.日期数据的处理,这个可以 添加 extension 解决

extension NSDate{

/*
几年几月 这个月的多少天
*/
class func getDaysInMonth( year: Int, month: Int) -> Int{ let calendar = NSCalendar.current let startComps = NSDateComponents()
startComps.day =
startComps.month = month
startComps.year = year let endComps = NSDateComponents()
endComps.day =
endComps.month = month == ? : month +
endComps.year = month == ? year + : year let startDate = calendar.date(from: startComps as DateComponents)
let endDate = calendar.date(from:endComps as DateComponents)! let diff = calendar.dateComponents([.day], from: startDate!, to: endDate) return diff.day!;
}
/*
几年几月 这个月的第一天是星期几
*/
class func firstWeekdayInMonth(year: Int, month: Int)->Int{ let calender = NSCalendar.current;
let startComps = NSDateComponents()
startComps.day =
startComps.month = month
startComps.year = year
let startDate = calender.date(from: startComps as DateComponents)
let firstWeekday = calender.ordinality(of: .weekday, in: .weekOfMonth, for: startDate!)
let week = firstWeekday! - ; return week ;
}
/*
今天是星期几
*/
func dayOfWeek() -> Int {
let interval = self.timeIntervalSince1970;
let days = Int(interval / );// 24*60*60
return (days - ) % ;
}
class func getCurrentDay() ->Int {

        let com = self.getComponents();
return com.day!
} class func getCurrentMonth() ->Int { let com = self.getComponents();
return com.month!
} class func getCurrentYear() ->Int { let com = self.getComponents();
return com.year!
} class func getComponents()->DateComponents{ let calendar = NSCalendar.current;
//这里注意 swift要用[,]这样方式写
let com = calendar.dateComponents([.year,.month,.day,.hour,.minute], from:Date());
return com
} }

2.视图部分,UI部分,用collectionview 更容易些

protocol CalenderControllerDelegate {

    func didSelectData(year:Int ,month:Int,day:Int)->Void
} class CalenderController: UIViewController ,UICollectionViewDelegate,UICollectionViewDataSource{ var delegate :CalenderControllerDelegate? var collection : UICollectionView!
let lastMonthButton = UIButton();
let calenderLabel = UILabel();
let nextMonthButton = UIButton(); var dateArray = ["日","一","二","三","四","五","六"];
let calenderCellId = "calenderCellId";
let dateCellId = "DateCellId"; var currentYear :Int = ;
var currentMonth :Int = ;
var currentDay :Int = ; var showYear :Int =
var showMonth :Int =
var showDay :Int = override func viewDidLoad() {
super.viewDidLoad() self.view.backgroundColor = UIColor.white;
currentYear = NSDate.getCurrentYear();
currentMonth = NSDate.getCurrentMonth();
currentDay = NSDate.getCurrentDay(); showYear = self.currentYear;
showMonth = self.currentMonth; self.addAllViews();
} override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
} func addAllViews(){ let frameWidth = self.view.frame.size.width;
let frameHeight = self.view.frame.size.height; let itemWidth = frameWidth / - ;
let itemHeight = itemWidth;
let layout = UICollectionViewFlowLayout();
layout.sectionInset = UIEdgeInsets.zero;
layout.itemSize = CGSize(width:itemWidth,height:itemHeight);
layout.minimumLineSpacing = ;
layout.minimumInteritemSpacing = ; collection = UICollectionView.init(frame:CGRect(x:,y: ,width:frameWidth,height:frameHeight / 1.5), collectionViewLayout: layout);
collection.center = self.view.center;
collection.delegate = self;
collection.dataSource = self;
collection.register(DateCell.self, forCellWithReuseIdentifier: dateCellId)
collection.register(CalenderCell.self, forCellWithReuseIdentifier: calenderCellId)
collection.backgroundColor = UIColor.white;
self.view.addSubview(collection); let collOriginY = collection.frame.origin.y;
let buttonHeight :CGFloat = ;
let buttonWidth = frameWidth / 3.0 lastMonthButton.frame = CGRect(x:,y:collOriginY - buttonHeight,width:buttonWidth,height:buttonHeight);
lastMonthButton.setTitle("<<上月", for: .normal);
lastMonthButton.setTitleColor(UIColor.black, for: .normal);
lastMonthButton.addTarget(self, action: #selector(CalenderController.lastMonthButtonAction), for: .touchUpInside)
self.view.addSubview(lastMonthButton); calenderLabel.frame = CGRect(x:buttonWidth ,y:lastMonthButton.frame.origin.y,width:buttonWidth,height:buttonHeight);
calenderLabel.textAlignment = .center;
calenderLabel.font = UIFont.systemFont(ofSize: );
calenderLabel.backgroundColor = UIColor(red: /, green: /, blue: /, alpha: );
self.view.addSubview(calenderLabel);
calenderLabel.font = UIFont.systemFont(ofSize: );
calenderLabel.text = String.init(format: "%d 年 %d 月 ", currentYear,currentMonth) nextMonthButton.frame = CGRect(x:buttonWidth * ,y:lastMonthButton.frame.origin.y,width:buttonWidth,height:buttonHeight);
nextMonthButton.setTitle("下月>>", for: .normal);
nextMonthButton.setTitleColor(UIColor.black, for: .normal);
nextMonthButton.addTarget(self, action: #selector(CalenderController.nextMonthButtonAction), for: .touchUpInside)
self.view.addSubview(nextMonthButton); let cancleBtn = UIButton();
self.view.addSubview(cancleBtn);
cancleBtn.setBackgroundImage(UIImage.init(named: "登录按钮"), for: .normal);
cancleBtn.setTitle("取消", for: .normal)
cancleBtn.addTarget(self, action: #selector(canckeAction), for: .touchUpInside);
cancleBtn.snp.makeConstraints { (make) in make.top.equalTo(collection.snp.bottom).offset();
make.centerX.equalToSuperview();
make.width.equalToSuperview().multipliedBy(0.3)
make.height.equalTo()
}
} @objc func canckeAction() -> Void { self.dismiss(animated: true) {}
} @objc func lastMonthButtonAction() -> Void { if showMonth == {
showMonth =
showYear -= ;
}else{
showMonth -= ;
}
calenderLabel.text = String.init(format: "%d 年 %d 月 ", showYear,showMonth)
collection.reloadData();
}
@objc func nextMonthButtonAction()->Void{ if showMonth == {
showMonth =
showYear += ;
}else{
showMonth += ;
}
calenderLabel.text = String.init(format: "%d 年 %d 月 ", showYear,showMonth)
collection.reloadData();
}
//collection view delegate
func numberOfSections(in collectionView: UICollectionView) -> Int {
return ;
} func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == {
return dateArray.count;
}
return
} func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath){ if indexPath.section == { let firstWeekDay = NSDate.firstWeekdayInMonth(year: showYear, month: showMonth);
let daysInThinsMonth = NSDate.getDaysInMonth(year: showYear, month: showMonth);
let index = indexPath.row; var day = ;
let regCell = cell as! CalenderCell regCell.label.backgroundColor = UIColor.white;
if index < firstWeekDay{ regCell.label.backgroundColor = UIColor.white;
regCell.label.text = "" }else if index > (firstWeekDay + daysInThinsMonth - ) { regCell.label.backgroundColor = UIColor.white;
regCell.label.text = "" }else {
day = index - firstWeekDay + ; regCell.label.text = String.init(format: "%d", day);
}
if showYear == currentYear && showMonth == currentMonth && day == currentDay{
regCell.label.backgroundColor = UIColor(red: /, green: /, blue: /, alpha: );
}else{
regCell.label.backgroundColor = UIColor.white;
} if showYear > currentYear || (showYear == currentYear && showMonth > currentMonth) || (showYear == currentYear && showMonth == currentMonth && day > currentDay){ regCell.label.textColor = UIColor.gray;
}else{
regCell.label.textColor = UIColor.black;
}
}
} func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: dateCellId, for: indexPath) as! DateCell;
cell.label.text = dateArray[indexPath.row];
return cell;
} let cell = collectionView.dequeueReusableCell(withReuseIdentifier: calenderCellId, for: indexPath) as! CalenderCell;
return cell;
} func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.section == {
return;
} let cell = collectionView.cellForItem(at: indexPath) as! CalenderCell;
let string = cell.label.text; if string == nil || string?.characters.count == {
return;
} let showDay = Int(string!)!
if showYear > currentYear || (showYear == currentYear && showMonth > currentMonth) || (showYear == currentYear && showMonth == currentMonth && showDay > currentDay){ return ;
}
if self.delegate != nil {
self.delegate?.didSelectData(year: showYear, month: showMonth, day: showDay);
}
self.dismiss(animated: true) {}
} } class CalenderCell: UICollectionViewCell { var label = UILabel() override init(frame: CGRect) {
super.init(frame: frame) label = UILabel.init(frame: self.bounds)
label.textAlignment = .center;
label.layer.cornerRadius = ;
label.layer.masksToBounds = true;
self.addSubview(label) } required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
} class DateCell: UICollectionViewCell { var label = UILabel() override init(frame: CGRect) {
super.init(frame: frame) label = UILabel.init(frame: self.bounds)
label.textAlignment = .center;
self.addSubview(label)
} required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

3.具体使用:::

        let vc = CalenderController();
vc.delegate = self;
self.present(vc, animated: true) { }; //calender delegate
func didSelectData(year: Int, month: Int, day: Int) { let timeString = String.init(format: "%d 年 %d 月 %d 日", year,month,day) }

swift 日历的制作的更多相关文章

  1. 基于jQuery日历插件制作日历

    这篇文章主要介绍了基于jQuery日历插件制作日历的相关资料,需要的朋友可以参考下 来看下最终效果图吧: 是长得丑了一点,不要吐槽我-.- 首先来说说这个日历主要的制作逻辑吧: ·一个月份最多有31天 ...

  2. vue - 小日历项目制作中的问题与解决思路

    效果图: 项目难点: 1. 每个月的日期数是不定的,拢共需要几个格子? 按照教程的做法需要42个.所以遍历数字42,得到42个div做格子. 2. 格子的排版怎么做? 顶部的星期布局使用的flex水平 ...

  3. 使用纯swift代码文件制作framework

    因为最近我们公司的一个客户要求我们使用swift编写程序并且将API封装成framework的形式提供给他们,所以我就开始了swift实践之路. 程序编写完之后,我就琢磨怎么封装成framework的 ...

  4. Swift - 使用CATransition制作过渡动画(页面切换转场效果)

    CATransition动画主要在过渡时使用,比如两个页面层级改变的时候添加一个转场效果.CATransition分为两类,一类是公开的动画效果,一类是非公开的动画效果. 1,公开动画效果: kCAT ...

  5. CSS3制作日历

    目标是制作如下面DEMO显示的一个日历效果: HTML Markup 先来看看其结构: <div class="calendar"> <span class=&q ...

  6. Swift语言实战晋级-第9章 游戏实战-跑酷熊猫-1

    学习目标 一.进一步学习Swift的游戏制作 二.掌握SKNode,SKSpriteNode的运用 三.了解SpriteKit的物理系统 四.掌握动作(SKAction)的运用 在这一章,我们要通过制 ...

  7. 学习swift语言的快速入门教程推荐

    随着苹果产品越来越火爆,苹果新推出的swift必定将在很大程度上代替oc语言.学好swift语言,对于IOS工程师来讲,已经是一门必备技能. 有一些比较好的英文版教程,值得学习. 1. Swift T ...

  8. CSS3制作

    目标是制作如下面DEMO显示的一个日历效果: HTML Markup 先来看看其结构: <div class="calendar"> <span class=&q ...

  9. 第43章 RTC—实时时钟

    第43章     RTC—实时时钟 全套200集视频教程和1000页PDF教程请到秉火论坛下载:www.firebbs.cn 野火视频教程优酷观看网址:http://i.youku.com/fireg ...

随机推荐

  1. Luogu3774 [CTSC2017]最长上升子序列 【Young表,根号分治】

    题目链接:洛谷 推荐阅读:2019年集训队论文<浅谈杨氏矩阵在信息学竞赛中的应用> 首先我们来看一个东西,叫做Young表. 它是长一个阶梯状的东西(行长和列长都是递减的),并且每一行和每 ...

  2. makefile通用模板(二)

    DIR_INC = ./include DIR_SRC = ./src DIR_OBJ = ./obj DIR_BIN = ./bin DIR_LIB = /home/exbot/lib LIBS = ...

  3. java使用freemark生成word/pdf

    目录 一. 背景 二.实现的技术选型以及遇到的坑 三.最终的效果 2.1 .doc word效果展示 2.1 .docx word效果展示 2.2 docx word转pdf效果展示 三.准备工作及代 ...

  4. 编译安装-httpd-2.2.15.tar.gz

    编译安装(又称源代码安装) 找到httpd-2.2.15.tar.gz安装包并拖到桌面root文件夹里 解包阶段 tar zxf httpd-2.2.15.tar.gz -C /usr/src 配置阶 ...

  5. Nginx:fastcgi_param详解

    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;#脚本文件请求的路径 fastcgi_param QUERY_STRI ...

  6. 【JVM】虚拟机字节码执行引擎

    概念模型上,典型的帧栈结构如下(栈是线程私有的,也就是每个线程都会有自己的栈).                     典型的帧栈结构 局部变量表 存放方法参数和方法内部定义的局部变量.在编译阶段, ...

  7. Redux遵循的三个原则是什么?

    (1)单一事实来源: 整个应用的状态存储在单个 store 中的对象/状态树里.单一状态树可以更容易地跟踪随时间的变化,并调试或检查应用程序. (2)状态是只读的: 改变状态的唯一方法是去触发一个动作 ...

  8. windows下更改Apache以fastcgi方式运行php

    Apache 默认 apache2handler 方式运行处理php. 下面说切换方法: 1.下载fastcgi模块,打开https://www.apachelounge.com/download/选 ...

  9. 分库分表 or NewSQL数据库?终于看懂应该怎么选!【转】

    最近与同行科技交流,经常被问到分库分表与分布式数据库如何选择,网上也有很多关于中间件+传统关系数据库(分库分表)与NewSQL分布式数据库的文章,但有些观点与判断是我觉得是偏激的,脱离环境去评价方案好 ...

  10. onenote架设在局域网服务器

    1.服务器端工作 1.1.在局域网服务器磁盘建个 文件夹,命名为 abc 1.2.右键共享,添加用户everyone 权限设置为可读写 不需要安装onenote 2.客户端工作 2.1.在客户端服务器 ...