制作日历步骤

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. C语言中一个字符对应一个ascii码;占一个1个字节8个二进制位;存到内存中也是用ascii的十进制的二进制表示

    /** 只读变量和常量 const 只读 const int a; int const a;//同上面的代码行是等价的,都表示一个常整形数. int *const a;//const具有"左 ...

  2. AtCoder Grand Contest 020 题解

    传送门 怎么又是\(tourist\)神仙的题-- \(A\) 咕咕 int n,a,b; int main(){ scanf("%d%d%d",&n,&a,&am ...

  3. mac中强大的快捷键

    用mac本不过一年左右, 但是越用越感觉到mac的强大. 只是从快捷键这个方面去说吧. 与 windows 系统的比较 从接触电脑开始, 就是与windows为伍, 最初的window98, xp 等 ...

  4. 修改windows网络参数,让上网更快

    管理员运行CMD,运行 netsh int tcp show global 查询活动状态... TCP 全局参数 ------------------------------------------- ...

  5. ehcache 配置说明

  6. Flask一种通用视图,增删改查RESTful API的设计

    模型设计是后端开发的第一步.数据模型反映了各种对象之间的相互关系. from app import db class Role(db.Model): """角色" ...

  7. tecplot三维模型绘制二维切片流线

    原视频下载地址链接: https://pan.baidu.com/s/1csugHK 密码: xrni

  8. Spring|@Autowired与new的区别

    前两天写代码的时候遇到一个问题,通过new出来的对象,自动注入的属性总是报空指针的错误.到网上查了资料,才发现问题所在,同时也加深了自己对于容器IOC的理解.现在把这个问题记录一下,仅供大家参考. [ ...

  9. Qualcomm Audio HAL 音频通路设置【转】

    本文转载自:https://blog.csdn.net/azloong/article/details/79383323 1. 音频框图概述| Front End PCMs | SoC DSP | B ...

  10. 完美解决: org.apache.ibatis.binding.BindingException Invalid bound statement (not found)

    异常描述: org.apache.ibatis.binding.BindingException: Invalid bound statement (not found) 原因: springboot ...