swift 日历的制作
制作日历步骤
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 日历的制作的更多相关文章
- 基于jQuery日历插件制作日历
这篇文章主要介绍了基于jQuery日历插件制作日历的相关资料,需要的朋友可以参考下 来看下最终效果图吧: 是长得丑了一点,不要吐槽我-.- 首先来说说这个日历主要的制作逻辑吧: ·一个月份最多有31天 ...
- vue - 小日历项目制作中的问题与解决思路
效果图: 项目难点: 1. 每个月的日期数是不定的,拢共需要几个格子? 按照教程的做法需要42个.所以遍历数字42,得到42个div做格子. 2. 格子的排版怎么做? 顶部的星期布局使用的flex水平 ...
- 使用纯swift代码文件制作framework
因为最近我们公司的一个客户要求我们使用swift编写程序并且将API封装成framework的形式提供给他们,所以我就开始了swift实践之路. 程序编写完之后,我就琢磨怎么封装成framework的 ...
- Swift - 使用CATransition制作过渡动画(页面切换转场效果)
CATransition动画主要在过渡时使用,比如两个页面层级改变的时候添加一个转场效果.CATransition分为两类,一类是公开的动画效果,一类是非公开的动画效果. 1,公开动画效果: kCAT ...
- CSS3制作日历
目标是制作如下面DEMO显示的一个日历效果: HTML Markup 先来看看其结构: <div class="calendar"> <span class=&q ...
- Swift语言实战晋级-第9章 游戏实战-跑酷熊猫-1
学习目标 一.进一步学习Swift的游戏制作 二.掌握SKNode,SKSpriteNode的运用 三.了解SpriteKit的物理系统 四.掌握动作(SKAction)的运用 在这一章,我们要通过制 ...
- 学习swift语言的快速入门教程推荐
随着苹果产品越来越火爆,苹果新推出的swift必定将在很大程度上代替oc语言.学好swift语言,对于IOS工程师来讲,已经是一门必备技能. 有一些比较好的英文版教程,值得学习. 1. Swift T ...
- CSS3制作
目标是制作如下面DEMO显示的一个日历效果: HTML Markup 先来看看其结构: <div class="calendar"> <span class=&q ...
- 第43章 RTC—实时时钟
第43章 RTC—实时时钟 全套200集视频教程和1000页PDF教程请到秉火论坛下载:www.firebbs.cn 野火视频教程优酷观看网址:http://i.youku.com/fireg ...
随机推荐
- 【HTML】行内元素与块级元素
一.行内元素与块级元素的三个区别 1.行内元素与块级元素直观上的区别 行内元素会在一条直线上排列,都是同一行的,水平方向排列 块级元素各占据一行,垂直方向排列.块级元素从新行开始结束接着一个断行. 2 ...
- Bzoj 2875: [Noi2012]随机数生成器(矩阵乘法)
2875: [Noi2012]随机数生成器 Time Limit: 10 Sec Memory Limit: 512 MB Submit: 2052 Solved: 1118 Description ...
- subcode
在思考.查阅subcode时,我发现Magma,Sage Math软件都提供了具体的命令和例子,对subcode的认识比较具象. 例如:Sage Math中有如下命令: C1 = codes.Hamm ...
- 游戏服务器与客户端交互,或者与跨服交互都有消息加密方式,为什么不明文传递,加md5校验呢
游戏服务器与客户端交互,或者与跨服交互都有消息加密方式,为什么不明文传递,加md5校验呢
- 【洛谷】P1275 魔板(暴力&思维)
题目描述 有这样一种魔板:它是一个长方形的面板,被划分成n行m列的n*m个方格.每个方格内有一个小灯泡,灯泡的状态有两种(亮或暗).我们可以通过若干操作使魔板从一个状态改变为另一个状态.操作的方式有两 ...
- VS2017打包注册IE插件及修改IE安全选项设置【转】
前言 最近项目需要在浏览器环境下读取员工身份证信息,要实现网页与硬件设备通信,考虑了几种实现方式: 1.借助ActiveX插件,通过程序库直接与设备通信. 优点:厂家提供了IE插件,开发简单 缺点:只 ...
- Java逻辑分页代码
前台jsp代码如下: <%@ page language="java" contentType="text/html; charset=UTF-8" pa ...
- Android 关于selector中item顺序的问题
selector的item从上到下是按照匹配原则来改变状态的,一旦匹配到某个item的状态,就不会继续往下匹配了. https://blog.csdn.net/l403040463/article/d ...
- jenkins持续集成springboot
1.可以配置项目标签 PS:这里Default Value值修改为master 2.代码地址,这里并没有拉取制定标签的代码,而是拉取了最新版本代码,如果要拉取指定标签代码需要把*/master修改成$ ...
- 快速识别Hash加密方式hashid
快速识别Hash加密方式hashid hashid工具是用来识别不同类型的散列加密,进而判断哈希算法的类型.该工具的而语法格式如下所示: hashid [option] INPUT 其中,option ...