swift 日历的制作

制作日历步骤

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, 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: 22);
        calenderLabel.backgroundColor =  UIColor(red: 41/255, green: 160/255, blue: 230/255, alpha: 1);
        self.view.addSubview(calenderLabel);
        calenderLabel.font = UIFont.systemFont(ofSize: 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)
    

    }
    

 

posted @ 2017-10-27 15:45  user_bo  阅读(1452)  评论(0编辑  收藏  举报