swift - 使用 iOS 中的事件填充 tableView (swift)

标签 swift ios8 tableview eventkit

我一直在关注“iOS8 Swift 编程手册”中关于 EventKit 和日历的部分,我学到了很多东西(特别是因为我是编程新手)。但我想要采取的下一步是用事件数据填充我在 ViewController 中具有导出的 TableView ,以便获得即将发生的事件的 TableView 列表。谁能告诉我该怎么做?

这是我到目前为止所拥有的:

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
}

现在我的事件正在完美地打印到控制台,但我不确定如何从那里到达 View Controller 中的 TableView 。如有任何帮助,我们将不胜感激!

最佳答案

首先,您的事件数据应该可以在表委托(delegate)中访问

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

但事件不是! 您可以在 readEvents 函数中在本地获取数据 尽管您为类(class)中的事件声明了一个存储,但您从未填充它

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

要填充类变量中的数据,只需删除“重新声明”

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

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

关于swift - 使用 iOS 中的事件填充 tableView (swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28482154/

相关文章:

ios - 将 AVFoundation 中的图像分配给 UIImageView 时,主视图中的 subview 崩溃

ios7 - "Could not instantiate class named UIStoryboardShowSegueTemplate"- 如何让 Storyboard对 iOS 7 和 iOS 8 满意?

iphone - iphone上tableview上的sqlite db上的文本搜索太慢了

ios - 在选项卡栏上 View Controller 的内容之前显示登录屏幕

swift - Realm 中每个对象的 Realm 对象通知

ios - 更改 Swift 中现有按钮的操作

swift - 当从一个 View Controller 转到另一个 View Controller (例如 Swift 中的 Instagram 或 Facebook)时,如何在 TableView 中保留当前的 ​​IndexPath.row?

ios - 无法将 moveRowAtIndexPath 用于 tableView

swift - 使用反斜杠符号在 swift 字符串中包含字典或数组值

ios - 结束更新后的 UITableView 部分页脚 View 位置