学习Swift有一个月了,动手写一个UIView吧。

所有源代码在最后,直接用就可以了,第一次写Swift,和C#,Java还是有区别的

(博客园可以考虑在代码插入中添加Swift的着色了)

1  函数准备。Swift的日历函数,随着版本的变化,变动很大。

    //MARK: - Calendar
//按照苹果的习惯,周日放在第一位
let weekdayForDisplay = ["周日","周一","周二","周三","周四","周五","周六"] //获取周 周日:1 - 周六:7
func getWeekDay(year:Int,month:Int,day:Int) ->Int{
let dateFormatter:NSDateFormatter = NSDateFormatter();
dateFormatter.dateFormat = "yyyy/MM/dd";
let date:NSDate? = dateFormatter.dateFromString(String(format:"%04d/%02d/%02d",year,month,day));
if date != nil {
let calendar:NSCalendar = NSCalendar.currentCalendar()
let dateComp:NSDateComponents = calendar.components(NSCalendarUnit.NSWeekdayCalendarUnit, fromDate: date!)
return dateComp.weekday;
}
return ;
} //这个月的最后一天
//先获得下个月的第一天,然后在此基础上减去24小时
//注意这里的时间Debug的时候是UTC
func getLastDay(var year:Int,var month:Int) -> Int?{
let dateFormatter:NSDateFormatter = NSDateFormatter();
dateFormatter.dateFormat = "yyyy/MM/dd";
if month == {
month =
year++
}
let targetDate:NSDate? = dateFormatter.dateFromString(String(format:"%04d/%02d/01",year,month+));
if targetDate != nil { let orgDate = NSDate(timeInterval:(**)*(-), sinceDate: targetDate!)
let str:String = dateFormatter.stringFromDate(orgDate)
return Int((str as NSString).componentsSeparatedByString("/").last!);
} return nil;
}

下面是NSDateCompents的一个坑,Swift 1 和 Swift 2 写法不一样

        let today = NSDate()
let calendar = NSCalendar(identifier: NSGregorianCalendar)
let comps:NSDateComponents = calendar!.components([NSCalendarUnit.Year,NSCalendarUnit.Month,NSCalendarUnit.Day], fromDate: today)

Swift 2 OptionSetType ,比较一下OC和Swift的写法

Objective-C

unsigned unitFlags = NSCalendarUnitYear
                   | NSCalendarUnitMonth
                   | NSCalendarUnitDay
                   | NSCalendarUnitWeekday
                   | NSCalendarUnitHour
                   | NSCalendarUnitMinute
                   | NSCalendarUnitSecond;

Swift
2.0

let unitFlags: NSCalendarUnit = [
.Year,
                                 
.Month,
                                 
.Day,
                                 
.Weekday,
                                 
.Hour,
                                 
.Minute,
                                 
.Second ]

Swift
1.2

let unitFlags: NSCalendarUnit =
.CalendarUnitYear
                              | .CalendarUnitMonth
                              | .CalendarUnitDay
                              | .CalendarUnitWeekday
                              | .CalendarUnitHour
                              | .CalendarUnitMinute
                              | .CalendarUnitSecond

Swift2.0 的语法和1.2有区别  
OptionSetType

2.接下来就是绘图,绘图就是各种被塞尔曲线

重点如下

如何居中

        let paragraph = NSMutableParagraphStyle()
        paragraph.alignment = NSTextAlignment.Center
       
let text  =  NSMutableAttributedString(string: weekdayForDisplay[i],attributes: [NSParagraphStyleAttributeName: paragraph])
        let CellRect = CGRect(x: leftside  , y:padding + mergin, width: WeekdayColumnWidth, height: RowHeight)
        text.drawInRect(CellRect) 红字粗体
        text.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(),range:NSMakeRange(,text.length))
        text.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(NSDefaultFontSize),range:NSMakeRange(,text.length))

3.接下来是如何捕获点击事件

由于是全手工绘制日历的格子,所以,就用OnTouchBegan事件的属性获得点击位置,根据位置得知被按下的区域隶属于哪个日子。

    //记录每天的格子的Rect
var DayRect = [Int:CGRect]() override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let SignleTouch = touches.first!
let Touchpoint = SignleTouch.locationInView(self)
let pick = getDayByTouchPoint(Touchpoint)
print("TouchPoint : X = \(Touchpoint.x) Y = \(Touchpoint.y) Day: \(pick)") if pick != {self.PickedDay = pick }
} //根据触摸点获取日期
func getDayByTouchPoint(touchpoint:CGPoint) -> Int {
for day in DayRect{
if day..contains(touchpoint){
return day.
}
}
return
}

最终效果如下图,可以实现点击选择日期。整个代码,8个小时可以完成。

现在的问题是,如果选择的日子变化了,我不知道怎么告诉上层的 ViewController,SelectDateChanged。

如果可以的话,最好能够出现 ActionConnection,可以拖曳连线,将Action和代码绑定。谁知道怎么做吗?

//
// CalendarView.swift
// PlanAndTarget
//
// Created by scs on 15/10/13.
// Copyright © 2015年 scs. All rights reserved.
// import UIKit @IBDesignable
class CalendarView: UIView {
//MARK: - Inspectable
@IBInspectable
var CurrentYear : Int = {
didSet{
if self.CurrentYear < {
self.CurrentYear =
}
setNeedsDisplay()
}
} @IBInspectable
var CurrentMonth : Int = {
didSet{
if self.CurrentMonth < || self.CurrentMonth > {
self.CurrentMonth =
}
setNeedsDisplay()
}
} @IBInspectable
var padding : CGFloat = {
didSet{
if (self.padding > ) {
self.padding =
}
setNeedsDisplay()
}
} @IBInspectable
var mergin : CGFloat = {
didSet{
if (self.mergin > ) {
self.mergin =
}
setNeedsDisplay()
}
} @IBInspectable
var RowHeight : CGFloat = {
didSet{
if (self.RowHeight > ) {
self.RowHeight =
}
setNeedsDisplay()
}
} @IBInspectable
var PickedDay : Int = {
didSet{
if (self.PickedDay < ){
self.PickedDay =
}
let lastDay = getLastDay( CurrentYear, month: CurrentMonth)
if (self.PickedDay > lastDay!){
self.PickedDay = lastDay!
}
setNeedsDisplay()
}
} //MARK: - Calendar
//按照苹果的习惯,周日放在第一位
let weekdayForDisplay = ["周日","周一","周二","周三","周四","周五","周六"] //获取周 周日:1 - 周六:7
func getWeekDay(year:Int,month:Int,day:Int) ->Int{
let dateFormatter:NSDateFormatter = NSDateFormatter();
dateFormatter.dateFormat = "yyyy/MM/dd";
let date:NSDate? = dateFormatter.dateFromString(String(format:"%04d/%02d/%02d",year,month,day));
if date != nil {
let calendar:NSCalendar = NSCalendar.currentCalendar()
let dateComp:NSDateComponents = calendar.components(NSCalendarUnit.NSWeekdayCalendarUnit, fromDate: date!)
return dateComp.weekday;
}
return ;
} //这个月的最后一天
//先获得下个月的第一天,然后在此基础上减去24小时
//注意这里的时间Debug的时候是UTC
func getLastDay(var year:Int,var month:Int) -> Int?{
let dateFormatter:NSDateFormatter = NSDateFormatter();
dateFormatter.dateFormat = "yyyy/MM/dd";
if month == {
month =
year++
}
let targetDate:NSDate? = dateFormatter.dateFromString(String(format:"%04d/%02d/01",year,month+));
if targetDate != nil { let orgDate = NSDate(timeInterval:(**)*(-), sinceDate: targetDate!)
let str:String = dateFormatter.stringFromDate(orgDate)
return Int((str as NSString).componentsSeparatedByString("/").last!);
} return nil;
} //MARK: - Event
//记录每天的格子的Rect
var DayRect = [Int:CGRect]() override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let SignleTouch = touches.first!
let Touchpoint = SignleTouch.locationInView(self)
let pick = getDayByTouchPoint(Touchpoint)
print("TouchPoint : X = \(Touchpoint.x) Y = \(Touchpoint.y) Day: \(pick)") if pick != {self.PickedDay = pick }
} //根据触摸点获取日期
func getDayByTouchPoint(touchpoint:CGPoint) -> Int {
for day in DayRect{
if day..contains(touchpoint){
return day.
}
}
return
} // Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) { let paragraph = NSMutableParagraphStyle()
paragraph.alignment = NSTextAlignment.Center
//查资料可知默认字体为12
let NSDefaultFontSize : CGFloat = ; //绘制表头
let UseableWidth :CGFloat = rect.width - (padding + mergin) * ;
let WeekdayColumnWidth : CGFloat = UseableWidth /
var leftside : CGFloat = padding + mergin
for i in ...{
let text = NSMutableAttributedString(string: weekdayForDisplay[i],attributes: [NSParagraphStyleAttributeName: paragraph])
let CellRect = CGRect(x: leftside , y:padding + mergin, width: WeekdayColumnWidth, height: RowHeight)
text.drawInRect(CellRect)
leftside += WeekdayColumnWidth
} //绘制当月每天
var rowCount = ;
leftside = padding + mergin
let today = NSDate()
let calendar = NSCalendar(identifier: NSGregorianCalendar)
let comps:NSDateComponents = calendar!.components([NSCalendarUnit.Year,NSCalendarUnit.Month,NSCalendarUnit.Day], fromDate: today) //Clear
DayRect.removeAll() for day in ...getLastDay(CurrentYear,month:CurrentMonth)!{
let weekday = getWeekDay(CurrentYear, month: CurrentMonth, day: day)
let text = NSMutableAttributedString(string: String(day), attributes: [NSParagraphStyleAttributeName: paragraph])
let LeftTopX = leftside + CGFloat(weekday - ) * WeekdayColumnWidth
let LeftTopY = padding + mergin + RowHeight * CGFloat(rowCount)
let CellRect :CGRect = CGRect(x: LeftTopX, y: LeftTopY, width: WeekdayColumnWidth, height: RowHeight)
if (PickedDay == day){
//选中的日子,UI效果
let PickRectPath = UIBezierPath(roundedRect: CellRect, cornerRadius: RowHeight/)
UIColor.blueColor().colorWithAlphaComponent(0.3).setFill()
PickRectPath.fill()
} if (comps.year == CurrentYear && comps.month == CurrentMonth && comps.day == day){
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(),range:NSMakeRange(,text.length))
text.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(NSDefaultFontSize),range:NSMakeRange(,text.length))
} text.drawInRect(CellRect)
DayRect[day] = CellRect
//绘制了周日之后,需要新的一行
if weekday == { rowCount++ }
} //绘制外框
let path : UIBezierPath = UIBezierPath(rect: CGRect(x: padding, y: padding, width: rect.width - padding * , height: padding + mergin + RowHeight * CGFloat(rowCount - ) + ))
path.stroke() //path = UIBezierPath(rect: CGRect(x: padding + mergin, y: padding + mergin, width: rect.width - (padding + mergin) * 2 , height: rect.height - (padding + mergin) * 2))
//path.stroke() print("LastDay Of 2015/10 : \(getLastDay(CurrentYear, month: CurrentMonth))" )
print("2015/10/18 : \(weekdayForDisplay[getWeekDay(CurrentYear, month: CurrentMonth, day: 18) - 1] )" )
print("Calendar Size Height: \(rect.height) Width: \(rect.width)" )
} }

iOs 自定义UIView 日历的实现 Swift2.1的更多相关文章

  1. IOS自定义UIView

    IOS中一般会用到几种方式自定义UIView 1.继承之UIView的存代码的自定义View 2.使用xib和代码一起使用的自定义View 3.存xib的自定义View(不需要业务处理的那种) 本文主 ...

  2. OpenGL ES: iOS 自定义 UIView 响应屏幕旋转

    iOS下使用OpenGL 如果使用GLKit View 那么不用担心屏幕旋转的问题,说明如下: If you change the size, scale factor, or drawable pr ...

  3. IOS xib和代码自定义UIView

    https://www.jianshu.com/p/1bcc29653085 总结的比较好 iOS开发中,我们常常将一块View封装起来,以便于统一管理内部的子控件. 下面就来说说自定义View的封装 ...

  4. 【iOS自定义键盘及键盘切换】详解

    [iOS自定义键盘]详解 实现效果展示: 一.实现的协议方法代码 #import <UIKit/UIKit.h> //创建自定义键盘协议 @protocol XFG_KeyBoardDel ...

  5. iOS自定义的UISwitch按钮

    UISwitch开关控件 开关代替了点选框.开关是到目前为止用起来最简单的控件,不过仍然可以作一定程度的定制化. 一.创建 UISwitch* mySwitch = [[ UISwitchalloc] ...

  6. iOS 自定义layer的两种方式

    在iOS中,你能看得见摸得着的东西基本都是UIView,比如一个按钮,一个标签,一个文本输入框,这些都是UIView: 其实UIView之所以能显示在屏幕上,完全是因为它内部的一个图层 在创建UIVi ...

  7. iOS自定义组与组之间的距离以及视图

    iOS自定义组与组之间的距离以及视图 //头视图高度 - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(N ...

  8. iOS 自定义转场动画

    代码地址如下:http://www.demodashi.com/demo/12955.html 一.总效果 本文记录分享下自定义转场动画的实现方法,具体到动画效果:新浪微博图集浏览转场效果.手势过渡动 ...

  9. iOS 自定义转场动画浅谈

    代码地址如下:http://www.demodashi.com/demo/11612.html 路漫漫其修远兮,吾将上下而求索 前记 想研究自定义转场动画很久了,时间就像海绵,挤一挤还是有的,花了差不 ...

随机推荐

  1. Ubuntu下解决adb devices:???????????? no permissions的方法

    之前一直都是在windows下进行开发的,但是这次由于一个小模块用的东西只能在linux下运行,所以就发生了这么一系列的问题环境:虚拟机Vmware下的Ubuntu12.10事件:连接android手 ...

  2. C#入门基础三

    封装:简化用户接口,隐藏实现细节. get{return 属性值:} set{属性值 = value:} 继承:子类继承父类所有非私有成员.继承具有传递性,单根性. 隐式继承:用引号(:)实现. 显示 ...

  3. C#入门基础二

    万物皆对象:对象是包含数据和操作的实体. 属性:名词     /  对象     \      方法:动词 ============================================== ...

  4. 爱上MVC~在Views的多级文件夹

    回到目录 在MVC里,你的控制器对应的视图一般是在Views目录,而如果希望在Views里再分几个模块文件夹默认是不允许的,我们需要做一下设置,就可以实现Views下的多次文件夹层次了,例如,我们有产 ...

  5. lua如何调用C++函数

    第一步是定义函数.所有在Lua中被调用的C/C++函数将使用下面一类指针进行调用: typedef int (*lua_CFunction) (lua_State *L); 换句话说,函数必须要以Lu ...

  6. fir.im Weekly - 94 个 iOS 开发资源推荐

    距离 2016 年还有 17 个日夜,而你和回家只隔了一张 12306 验证码的距离,祝大家抢票顺利.本期 fir.im Weekly 收集了一些优秀的 GitHub 源码.开发工具和动画特效,希望对 ...

  7. SSM环境搭建(接口编程方式)

    一直用ssm在开发项目,之前都是直接copy别人的项目,今天趁着项目刚刚交付,自己搭建一下ssm环境,做个记录 一.创建项目.引入jar包,因为版本不一样,就不贴出这部分的内容了.个人平时的习惯是,先 ...

  8. Design5:Sql server 文件组和文件

    1,文件组和文件的作用 Sql Server的数据存储在文件中,文件是实际存储数据的物理实体,文件组是逻辑对象,Sql server通过文件组来管理文件. 一个DataBase有一个或多个FileGr ...

  9. Chrome开发者工具之JavaScript内存分析

    阅读目录 对象大小(Object sizes) 对象的占用总内存树 支配对象(Dominators) V8介绍 Chrome 任务管理器 通过DevTools Timeline来定位内存问题 内存回收 ...

  10. 《BI那点儿事》Microsoft 时序算法——验证神奇的斐波那契数列

    斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10 ...