通过内置的iOS日历以编程方式快速创建/访问日历

时间:2018-09-01 10:25:03

标签: ios swift uikit eventkit

我正在尝试在我的应用程序中创建自定义日历,并找到了有关构建自定义日历(https://github.com/patchthecode/JTAppleCalendar)的教程,我在一个新项目中进行了跟踪,并且该教程可以正常工作。但是,本教程使用情节提要,而我的应用程序则没有。因此,我尝试使用子视图将情节提要UI设置迁移到代码中,但未成功。

此功能的目的是将商务会议存储在日历中,我愿意放弃自定义日历功能并访问iOS日历,但是我不确定如何执行此操作。

当我尝试运行此错误时出现的错误是线程1:致命错误:在view.addSubview(calendarView)处展开一个可选值时,意外地发现了nil

该应用程序使用TabBarController进行导航,管理器是我的标签之一。

在使自定义日历工作或我可以使用哪些代码访问iOS日历方面的任何帮助,将不胜感激。

下面的代码。

import UIKit
import JTAppleCalendar
import EventKit
class Organiser: UIViewController {

var calendarView: JTAppleCalendarView!
var year: UILabel!
var month: UILabel!

let outsideMonthColour = UIColor.white
let monthColour = UIColor.black
let selectedMonthColour = UIColor.red
let currentDateSelectedColour = UIColor.blue


let formatter = DateFormatter()

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(calendarView)
    view.addSubview(year)
    view.addSubview(month)


    calendarView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive=true
    calendarView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive=true
    calendarView.heightAnchor.constraint(equalToConstant: 200)
    calendarView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: -30)

    month.bottomAnchor.constraint(equalTo: calendarView.topAnchor, constant: 25)
    month.leftAnchor.constraint(equalTo: calendarView.leftAnchor, constant: 0)


    year.bottomAnchor.constraint(equalTo: month.topAnchor, constant: 25)
    year.leftAnchor.constraint(equalTo: month.leftAnchor, constant: 25)

    calendarView.translatesAutoresizingMaskIntoConstraints = false
    month.translatesAutoresizingMaskIntoConstraints = false
    year.translatesAutoresizingMaskIntoConstraints = false

    // Do any additional setup after loading the view, typically from a nib.
}


//setup calendar cells
func setupCalendarView(){
    calendarView.minimumLineSpacing = 0
    calendarView.minimumInteritemSpacing = 0

    calendarView.visibleDates { visibleDates in
        self.setupViewsOfCalendar(from: visibleDates)
    }
}

//setup selected cell text colour function
func handleCellTextColour(view: JTAppleCell?, cellState: CellState){
    guard let validCell = view as? CustomCell else { return }

    if cellState.isSelected {
        validCell.dateLabel?.textColor = currentDateSelectedColour
    } else {
        if cellState.dateBelongsTo == .thisMonth {
            validCell.dateLabel?.textColor = monthColour
        } else {
            validCell.dateLabel?.textColor = outsideMonthColour
        }
    }

}

//setup selected cell highlight function
func handleCellSelected(view: JTAppleCell?, cellState: CellState){
    guard let validCell = view as? CustomCell else { return }

    if cellState.isSelected {
        validCell.selectedView?.isHidden = false
    } else {
        validCell.selectedView?.isHidden = true
    }
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}


extension Organiser: JTAppleCalendarViewDataSource{
func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {
    formatter.dateFormat = "yyyy mm dd"
    formatter.timeZone = Calendar.current.timeZone
    formatter.locale = Calendar.current.locale

    let startDate = formatter.date(from: "2017 01 01")
    let endDate = formatter.date(from: "2018 12 31")

    let parameters = ConfigurationParameters(startDate: startDate!, endDate: endDate!)
    return parameters
}

}


extension Organiser: JTAppleCalendarViewDelegate{

func calendar(_ calendar: JTAppleCalendarView, willDisplay cell: JTAppleCell, forItemAt date: Date, cellState: CellState, indexPath: IndexPath) {
    let myCustomCell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
    myCustomCell.dateLabel?.text = cellState.text

    handleCellSelected(view: cell, cellState: cellState)
    handleCellTextColour(view: cell, cellState: cellState)
    return ()
}

func calendar(_ calendar: JTAppleCalendarView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTAppleCell {
    let myCustomCell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
    self.calendar(calendar, willDisplay: myCustomCell, forItemAt: date, cellState: cellState, indexPath: indexPath)
    myCustomCell.dateLabel?.text = cellState.text
    return myCustomCell
}
//function for handling interface changes when cell selected
func calendar(_ calendar: JTAppleCalendarView, didSelectDate date: Date, cell: JTAppleCell?, cellState: CellState) {
    handleCellSelected(view: cell, cellState: cellState)
    handleCellTextColour(view: cell, cellState: cellState)
}
//function for handling interface changes when cell deselected selected
func calendar(_ calendar: JTAppleCalendarView, didDeselectDate date: Date, cell: JTAppleCell?, cellState: CellState) {
    handleCellSelected(view: cell, cellState: cellState)
    handleCellTextColour(view: cell, cellState: cellState)
}
//function so that month and year show when calendar loads
func setupViewsOfCalendar(from visibleDates: DateSegmentInfo){
    let date = visibleDates.monthDates.first!.date

    self.formatter.dateFormat = "yyyy"
    self.year.text = self.formatter.string(from: date)

    self.formatter.dateFormat = "MMMM"
    self.month.text = self.formatter.string(from: date)
}

//function to change month when calendar scrolled
func calendar(_ calendar: JTAppleCalendarView, didScrollToDateSegmentWith visibleDates: DateSegmentInfo) {
    let date = visibleDates.monthDates.first!.date

    formatter.dateFormat = "yyyy"
    year.text = formatter.string(from: date)

    formatter.dateFormat = "MMMM"
    month.text = formatter.string(from: date)
}

}

2 个答案:

答案 0 :(得分:0)

您遇到的崩溃是因为您没有初始化JTAppleCalendarView,所以当您尝试将其添加为子视图时,它为nil。编译器不会抱怨,因为您在声明中强行将其展开。

替换

var markerAdded =  0;

var text = document.getElementById('searchtext');

function myMap() {
  var myCenter = new google.maps.LatLng(56.1304, -106.3468);
  var mapProp = {
    center: myCenter,
    zoom: 6,
    scrollwheel: true,
    draggable: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map"), mapProp);

   google.maps.event.addListener(map, 'click', function (event)     {
      if (markerAdded == 0 ){
        placeMarker(event.latLng);
        markerAdded = 1;
      }
    });

  google.maps.event.addListener(map, 'mousemove', function (event) {    
         text.value = location.lat() + ' ' + location.lng(); 
  }

    function placeMarker(location) {
        var marker = new google.maps.Marker({
            position: location,
            animation: google.maps.Animation.DROP,
            map: map
        });

     text.value = location.lat() + ' ' + location.lng(); 
    }
}

使用

var calendarView: JTAppleCalendarView!

请注意,当您尝试将年和月标签添加为子视图时,在下两行中也会由于相同的原因而崩溃。

您可以将其声明替换为:

let calendarView = JTAppleCalendarView()

答案 1 :(得分:0)

您通过使用“!”强制展开JTAppleCalendar的实例。因此,如果值是nil,则在强制展开时,应用程序将崩溃。为避免这种情况,您需要执行以下步骤。

步骤1 :您可以将对象库中的UIView添加到xib或情节提要中。

第2步:然后,需要按照下图所示在Identity Inspector中设置JTAppleCalenderView。enter image description here

然后,您可以使用与以前相同的代码,并且它不会崩溃。

注意:您还需要在UILabel中添加相同的内容,以免UILabel崩溃。