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 ...
随机推荐
- window的pid为4的system进程占用80端口的解决办法
1.taskkill /pid 4 /f 无法终止进程占用80端口的进程时,运行 net stop http(若是第一次运行不能终止所有服务,继续运行该命令)
- (尚003).Vue_模板语法
1.双大括号表达式 2.指令一:强制数据绑定 3.指令二;绑定事件监听 test003.html<!DOCTYPE html><html lang="en"> ...
- RS译码的描述
在描述Reed-Solomon码的译码时,需要确定错误多项式的系数,然后进行搜索.通常,错误多项式的最高次数与错误的符号数相同. 如: λ(X)= λ0+ λ1X+ ...+ λνXν. 设该RS码最 ...
- go type别名和定义类型区别
package main import ( "fmt" ) type person struct { age int name string } func (p person)te ...
- 无旋Treap模板
传送门 Code #include<bits/stdc++.h> #define ll long long #define max(a,b) ((a)>(b)?(a):(b)) # ...
- CFD计算过程发散诸多原因分析【转载】
转载自: http://blog.sina.com.cn/s/blog_5fdfa7e601010rkx.html 今天探讨引起CFD计算过程中发散的一些原因.cfd计算是将描述物理问题的偏微分方程转 ...
- Prometheus初体验(三)
一.安装部署 Prometheus基于Golang编写,编译后的软件包,不依赖于任何的第三方依赖.用户只需要下载对应平台的二进制包,解压并且添加基本的配置即可正常启动Prometheus Server ...
- LeetCode 第 155 场周赛
一.最小绝对差(LeetCode-5189) 1.1 题目描述 1.2 解题思路 数组排好序,获取最小的差值即可. 1.3 解题代码 public class Solution { class Tes ...
- ubuntu之路——day10.3 train/dev/test的划分、大小和指标更新
train/dev/test的划分 我们在前面的博文中已经提到了train/dev/test的相关做法.比如不能将dev和test混为一谈.同时要保证数据集的同分布等. 现在在train/dev/t ...
- python反射hasattr getattr setattr delattr
反射 : 是用字符串类型的名字 去操作 变量 相比于用eval('print(name)') 留有 安全隐患 反射 就没有安全问题 hasattr 语法: hasattr(object, name)o ...