博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
swift 日历的制作
阅读量:4321 次
发布时间:2019-06-06

本文共 10762 字,大约阅读时间需要 35 分钟。

制作日历步骤

1.日期数据的处理,这个可以 添加 extension 解决

extension NSDate{   /* 几年几月 这个月的多少天 */    class func getDaysInMonth( year: Int, month: Int) -> Int{                let calendar = NSCalendar.current                let startComps = NSDateComponents()        startComps.day = 1        startComps.month = month        startComps.year = year                let endComps = NSDateComponents()        endComps.day = 1        endComps.month = month == 12 ? 1 : month + 1        endComps.year = month == 12 ? year + 1 : 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 = 1        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! - 1;                return week ;    }
/* 今天是星期几 */    func dayOfWeek() -> Int {        let interval = self.timeIntervalSince1970;        let days = Int(interval / 86400);// 24*60*60        return (days - 3) % 7;    }
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 = 2017;    var currentMonth :Int = 10;    var currentDay :Int = 23;        var showYear :Int = 0    var showMonth :Int = 0    var showDay :Int = 0        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 / 7 - 5;        let itemHeight = itemWidth;        let layout = UICollectionViewFlowLayout();        layout.sectionInset = UIEdgeInsets.zero;        layout.itemSize = CGSize(width:itemWidth,height:itemHeight);        layout.minimumLineSpacing = 2;        layout.minimumInteritemSpacing = 2;                collection = UICollectionView.init(frame:CGRect(x:0,y:0 ,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 = 40;        let buttonWidth = frameWidth / 3.0                lastMonthButton.frame = CGRect(x:0,y:collOriginY - buttonHeight,width:buttonWidth,height:buttonHeight);        lastMonthButton.setTitle("<
<上月", for: .normal); lastmonthbutton.settitlecolor(uicolor.black, lastmonthbutton.addtarget(self, action: #selector(calendercontroller.lastmonthbuttonaction), .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:" 22); calenderlabel.backgroundcolor="UIColor(red:" 41 255, green: 160 blue: 230 alpha: 1); self.view.addsubview(calenderlabel); 13); calenderlabel.text="String.init(format:" "%d 年 %d 月 ", currentyear,currentmonth) nextmonthbutton.frame="CGRect(x:buttonWidth" * 2,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(10); make.centerX.equalToSuperview(); make.width.equalToSuperview().multipliedBy(0.3) make.height.equalTo(30) } } @objc func canckeAction() -> Void { self.dismiss(animated: true) {} } @objc func lastMonthButtonAction() -> Void { if showMonth == 1 { showMonth = 12 showYear -= 1; }else{ showMonth -= 1; } calenderLabel.text = String.init(format: "%d 年 %d 月 ", showYear,showMonth) collection.reloadData(); } @objc func nextMonthButtonAction()->Void{ if showMonth == 12 { showMonth = 1 showYear += 1; }else{ showMonth += 1; } calenderLabel.text = String.init(format: "%d 年 %d 月 ", showYear,showMonth) collection.reloadData(); } //collection view delegate func numberOfSections(in collectionView: UICollectionView) -> Int { return 2; } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == 0{ return dateArray.count; } return 42 } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath){ if indexPath.section == 1{ let firstWeekDay = NSDate.firstWeekdayInMonth(year: showYear, month: showMonth); let daysInThinsMonth = NSDate.getDaysInMonth(year: showYear, month: showMonth); let index = indexPath.row; var day = 0; 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 - 1) { regCell.label.backgroundColor = UIColor.white; regCell.label.text = "" }else { day = index - firstWeekDay + 1; regCell.label.text = String.init(format: "%d", day); } if showYear == currentYear && showMonth == currentMonth && day == currentDay{ regCell.label.backgroundColor = UIColor(red: 225/255, green: 75/255, blue: 6/255, alpha: 1); }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 == 0{ 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 == 0 { return; } let cell = collectionView.cellForItem(at: indexPath) as! CalenderCell; let string = cell.label.text; if string == nil || string?.characters.count == 0{ 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 = 15; 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)        }

 

转载于:https://www.cnblogs.com/Bob-blogs/p/7743692.html

你可能感兴趣的文章
教育行业安全无线网络解决方案
查看>>
7个杀手级的开源监测工具
查看>>
软件架构学习小结
查看>>
C语言实现UrlEncode编码/UrlDecode解码
查看>>
返回用户提交的图像工具类
查看>>
树链剖分 BZOJ3589 动态树
查看>>
挑战程序设计竞赛 P131 区间DP
查看>>
【例9.9】最长公共子序列
查看>>
S02_CH02_MIO实验Enter a post title
查看>>
javascript 字符串去空格
查看>>
NSFileManager打印目录下的文件的函数
查看>>
Rails--bundle exec rake db:migrate
查看>>
第二组骆阳洋通信工程三班抓包分析
查看>>
深度优先搜索 之 CODE[VS] 1116 四色问题
查看>>
浏览器渲染过程
查看>>
js遍历Object所有属性
查看>>
再也不学AJAX了!(三)跨域获取资源 ③ - WebSocket & postMessage
查看>>
pycharm设置python文件颜色
查看>>
不换行输出的两种方式
查看>>
贵在坚持不懈
查看>>