使用来自 iOS (swift) 的事件填充 tableView

Populate tableView with events from iOS (swift)

我一直在关注 "iOS8 Swift Programming Cookbook" 关于 EventKit 和日历的部分,并且学到了很多东西(特别是因为我是编程新手)。但是我想采取的下一步是用事件数据填充一个表视图,我在 ViewController 中有一个出口,以便有一个即将发生的事件的表视图列表。谁能告诉我该怎么做?

这是我目前的情况:

import UIKit
import EventKit
import EventKitUI


class TodayViewController: UIViewController, UITableViewDataSource {

var events: AnyObject = []

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    requestCalendarAccess()

}

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


func requestCalendarAccess() {

    let eventStore = EKEventStore()


    switch EKEventStore.authorizationStatusForEntityType(EKEntityTypeEvent){

    case .Authorized:
        readEvents()
    case .Denied:
        displayAccessDenied()
    case .NotDetermined:
        eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion:
            {[weak self] (granted: Bool, error: NSError!) -> Void in
                if granted{
                    self!.readEvents()
                } else {
                    self!.displayAccessDenied()
                }
        })
    case .Restricted:
        displayAccessRestricted()
    }
}


func displayAccessDenied(){
    println("Access to the event store is denied.")
}

func displayAccessRestricted(){
    println("Access to the event store is restricted.")
}

func readEvents(){

    /* Instantiate the event store */
    let eventStore = EKEventStore()

    let icloudSource = sourceInEventStore(eventStore,
        type: EKSourceTypeCalDAV,
        title: "iCloud")

    if icloudSource == nil{
        println("You have not configured iCloud for your device.")
        return
    }

    let calendar = calendarWithTitle("Work",
        type: EKCalendarTypeCalDAV,
        source: icloudSource!,
        eventType: EKEntityTypeEvent)

    if calendar == nil{
        println("Could not find the calendar we were looking for.")
        return
    }

    /* The event starts from today, right now */
    let startDate = NSDate()

    /* The end date will be 1 day from today */
    let endDate = startDate.dateByAddingTimeInterval(24 * 60 * 60)

    /* Create the predicate that we can later pass to the
    event store in order to fetch the events */
    let searchPredicate = eventStore.predicateForEventsWithStartDate(
        startDate,
        endDate: endDate,
        calendars: [calendar!])

    /* Fetch all the events that fall between
    the starting and the ending dates */
    let events = eventStore.eventsMatchingPredicate(searchPredicate)
        as [EKEvent]

    if events.count == 0 {
        println("No events could be found")
    } else {

        // Go through all the events and print them to the console
        for event in events{

            println("Event title = \(event.title)")
            println("Event start date = \(event.startDate)")
            println("Event end date = \(event.endDate)")
        }
    }

}

func sourceInEventStore(
    eventStore: EKEventStore,
    type: EKSourceType,
    title: String) -> EKSource?{

        for source in eventStore.sources() as [EKSource]{
            if source.sourceType.value == type.value &&
                source.title.caseInsensitiveCompare(title) ==
                NSComparisonResult.OrderedSame{
                    return source
            }
        }

        return nil
}

func calendarWithTitle(
    title: String,
    type: EKCalendarType,
    source: EKSource,
    eventType: EKEntityType) -> EKCalendar?{

        for calendar in source.calendarsForEntityType(eventType).allObjects
            as [EKCalendar]{
                if calendar.title.caseInsensitiveCompare(title) ==
                    NSComparisonResult.OrderedSame &&
                    calendar.type.value == type.value{
                        return calendar
                }
        }

        return nil
}



func tableView(tableView: UITableView,
    numberOfRowsInSection section: Int) -> Int {
        return events.count
}


func tableView(tableView: UITableView,
    cellForRowAtIndexPath
    indexPath: NSIndexPath) -> UITableViewCell {

        let cell =
        tableView.dequeueReusableCellWithIdentifier("cell")
            as UITableViewCell


        cell.textLabel!.text = /*what goes here?*/
        return cell
}

现在我的事件正在完美地打印到控制台,但我不确定如何从那里到我的视图控制器中的表视图。感谢您的帮助!

函数

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell

获取参数 cellForRowAtIndexPath,其中包含表视图中行的索引。您可以使用 indexPath.row 访问该索引,您应该使用它来访问您的 events-Array.

因此,例如您的函数可能如下所示:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

    var event = self.events[indexPath.row]

    cell.textLabel!.text = event.eventIdentifier

    return cell
}

我不知道 EKEvent Class 到底是什么样子,但是 Apple 的文档 class 说有 eventIdentifier 类型 String 所以你可以用你的 tableview 来测试它。

希望您喜欢编程! :)

首先你的事件数据应该可以在你的table委托中访问

func readEvents(){
...
let events = eventStore.eventsMatchingPredicate(searchPredicate)
        as [EKEvent]
...
}

但事件不是 !!! 你只在本地获取你的数据在你的函数 readEvents 中 尽管您在 class 中为事件声明了一个商店,但您从未填写过它

class TodayViewController: UIViewController, UITableViewDataSource {
var events: AnyObject = []
...
}

要在您的 class 变量中填充数据,只需删除 'redeclaration'

    ...
    var events: [EKEvent] = []    

    func readEvents(){
        ...
        events = eventStore.eventsMatchingPredicate(searchPredicate)
                as [EKEvent]
        ...
     }