麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 學院 > 開發設計 > 正文

iOs自定義UIView日歷的實現Swift2.1

2019-11-14 18:09:21
字體:
來源:轉載
供稿:網友

學習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 0;    }        //這個月的最后一天    //先獲得下個月的第一天,然后在此基礎上減去24小時    //注意這里的時間Debug的時候是UTC    func getLastDay(var year:Int,var month:Int) -> Int?{        let dateFormatter:NSDateFormatter = NSDateFormatter();        dateFormatter.dateFormat = "yyyy/MM/dd";        if month == 12 {            month = 0            year++        }        let targetDate:NSDate? = dateFormatter.dateFromString(String(format:"%04d/%02d/01",year,month+1));        if targetDate != nil {                        let orgDate = NSDate(timeInterval:(24*60*60)*(-1), 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;

Swift2.0

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

Swift1.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(0,text.length))        text.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(NSDefaultFontSize),range:NSMakeRange(0,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 != 0 {self.PickedDay = pick }    }        //根據觸摸點獲取日期    func getDayByTouchPoint(touchpoint:CGPoint) -> Int {        for day in DayRect{            if day.1.contains(touchpoint){                return day.0            }        }        return 0    }

 

最終效果如下圖,可以實現點擊選擇日期。整個代碼,8個小時可以完成。

現在的問題是,如果選擇的日子變化了,我不知道怎么告訴上層的 ViewController,SelectDateChanged。

如果可以的話,最好能夠出現 ActionConnection,可以拖曳連線,將Action和代碼綁定。誰知道怎么做嗎?

////  CalendarView.swift//  PlanAndTarget////  Created by  scs on 15/10/13.//  Copyright © 2015年  scs. All rights reserved.//import UIKit@IBDesignableclass CalendarView: UIView {    //MARK: - Inspectable    @IBInspectable    var CurrentYear : Int = 2015{        didSet{            if self.CurrentYear < 0 {                self.CurrentYear = 2015            }            setNeedsDisplay()        }    }        @IBInspectable    var CurrentMonth : Int = 10 {        didSet{            if self.CurrentMonth < 0 || self.CurrentMonth > 12 {                self.CurrentMonth = 1            }            setNeedsDisplay()        }    }        @IBInspectable    var padding : CGFloat = 4 {        didSet{            if (self.padding > 50 ) {                self.padding = 50            }            setNeedsDisplay()        }    }        @IBInspectable    var mergin : CGFloat = 4 {        didSet{            if (self.mergin > 50 ) {                self.mergin = 50            }            setNeedsDisplay()        }    }        @IBInspectable    var RowHeight : CGFloat = 20{        didSet{            if (self.RowHeight > 100 ) {                self.RowHeight = 100            }            setNeedsDisplay()        }    }        @IBInspectable    var PickedDay : Int = 1 {        didSet{            if (self.PickedDay < 0){                self.PickedDay = 1            }            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 0;    }        //這個月的最后一天    //先獲得下個月的第一天,然后在此基礎上減去24小時    //注意這里的時間Debug的時候是UTC    func getLastDay(var year:Int,var month:Int) -> Int?{        let dateFormatter:NSDateFormatter = NSDateFormatter();        dateFormatter.dateFormat = "yyyy/MM/dd";        if month == 12 {            month = 0            year++        }        let targetDate:NSDate? = dateFormatter.dateFromString(String(format:"%04d/%02d/01",year,month+1));        if targetDate != nil {                        let orgDate = NSDate(timeInterval:(24*60*60)*(-1), 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 != 0 {self.PickedDay = pick }    }        //根據觸摸點獲取日期    func getDayByTouchPoint(touchpoint:CGPoint) -> Int {        for day in DayRect{            if day.1.contains(touchpoint){                return day.0            }        }        return 0    }            // 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 = 12;                //繪制表頭        let UseableWidth :CGFloat = rect.width - (padding + mergin) * 2;        let WeekdayColumnWidth : CGFloat = UseableWidth / 7        var leftside  : CGFloat = padding + mergin        for i in 0...6{            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 = 1;        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 1...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 - 1) * 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/2)                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(0,text.length))                text.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(NSDefaultFontSize),range:NSMakeRange(0,text.length))            }                                    text.drawInRect(CellRect)            DayRect[day] = CellRect            //繪制了周日之后,需要新的一行            if weekday == 7 { rowCount++ }        }                //繪制外框        let path : UIBezierPath = UIBezierPath(rect: CGRect(x: padding, y: padding, width: rect.width - padding * 2 , height: padding + mergin + RowHeight * CGFloat(rowCount - 1) + 10 ))        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)" )    }            }

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 91看片淫黄大片欧美看国产片 | 欧美韩国日本在线 | 欧美亚洲国产成人综合在线 | 极品一级片 | 久久精品成人影院 | 亚洲精品免费播放 | 精品麻豆cm视频在线看 | 国内精品视频饥渴少妇在线播放 | 日韩午夜片 | 日韩av电影免费在线观看 | 91在线播放国产 | 一区二区三区国产在线 | 亚洲国产一区二区三区 | 中文字幕欧美日韩 | 男女亲热网站 | 欧美特黄一级高清免费的香蕉 | 亚洲视频在线网 | 在线看免费观看av | 久久免费视频5 | 深夜福利久久久 | 2021狠狠操 | 一级毛片播放 | 黄色片在线播放 | 欧美成人午夜精品久久久 | 男女无遮挡羞羞视频 | 久草成人在线观看 | 色网站综合 | 午夜免费网| 国产成人精品无人区一区 | 久久精品一区二区三区四区五区 | 精品国产乱码久久久久久久 | 国产精品剧情一区二区三区 | 日韩精品a在线观看 | 亚洲成人自拍电影 | 黄色免费在线视频网站 | 久久精品一级片 | 久久久久久久一区二区 | 男男羞羞视频网站国产 | 国产精品一区二区三区在线 | 亚洲综合无码一区二区 | 色中色激情影院 |