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 ...
随机推荐
- C# 调用 C++ Dll 类型转换的方式 全
摘要:C#引用C++ Dll 所有类型转换的方式 //C++中的DLL函数原型为 //extern "C" __declspec(dllexport ...
- 玩好JDK[转]
ref: https://www.cnblogs.com/zuoxiaolong/p/life53.html java-reference:https://docs.oracle.com/en/jav ...
- CF1214题解
D 因为可以用贡献2把起点终点堵掉,所以答案为0/1/2 0/2简单 1:方格可以理解为分层图,考虑每个能到达终点,起点能到达其的点,标记一下,对角线如果仅存在1则为必经之路 E \(d_i\le n ...
- csapp网络编程初学笔记
csapp网络编程初学笔记 客户端-服务器编程模型 每个网络应用都是基于客户端-服务器模型,服务器管理某种资源,并且通过操作来为它的客户提供某种服务 客户端-服务器模型中的基本操作是transacti ...
- git 删除文件 、只删除远程仓库文件、更换远程仓库
一.删除文件 1.克隆远程仓库到本地库. 例如使用ssh方法: git clone git@github.com:xxx/xxx.git 2.对需要删除的文件.文件夹进行如下操作: git rm te ...
- Spark(四十六):Spark 内存管理之—OFF_HEAP
存储级别简介 Spark中RDD提供了多种存储级别,除去使用内存,磁盘等,还有一种是OFF_HEAP,称之为 使用JVM堆外内存 https://github.com/apache/spark/blo ...
- 如何将eclipse项目导入到idea
intellij idea中文资料网上比较少,对于eclipse的项目如何导入intellij idea也没有完整的说明,本人在这里整理下,方便更多人加入到intellij idea的阵容里. 直接上 ...
- phpexcel 导出xsl乱码
在header前面加上 ob_end_clean(); ob_end_clean();//清除缓冲区,避免乱码 header('Content-Type: application/vnd.ms-exc ...
- ArcPy python实例教程-条件平差-测量平差
ArcPy python实例教程-条件平差-测量平差 商务合作,科技咨询,版权转让:向日葵,135-4855__4328,xiexiaokui#qq.com 输入参数:条件方程的系数,观测值,常数项和 ...
- 范围指示器Extent Indicators
范围指示器Extent Indicators 商务合作,科技咨询,版权转让:向日葵,135-4855__4328,xiexiaokui#qq.com 商务合作,科技咨询,版权转让:向日葵,135- ...