import UIKit
import EventKit
class EventThisWeekController: UITableViewController {
var eventStore: EKEventStore = EKEventStore()
var eventsThisWeek: [EKEvent] = []
override func viewDidLoad() {
super.viewDidLoad()
self.eventStore.requestAccessToEntityType(.Event) {
(granted, error) -> Void in
guard granted else { fatalError("Permission denied") }
let endDate = NSDate(timeIntervalSinceNow: 604800)
let predicate = self.eventStore.predicateForEventsWithStartDate(NSDate(),
endDate: endDate,
calendars: nil)
self.eventsThisWeek = self.eventStore.eventsMatchingPredicate(predicate)
print(self.eventsThisWeek.count)
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("cellForRowAtIndexPath")
let cell = UITableViewCell(style: .Default, reuseIdentifier: nil)
cell.textLabel?.text = self.eventsThisWeek[indexPath.row].title
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("numberOfRowsInSection")
return eventsThisWeek.count
}
}
数据源和委托被分配给此Controller,EvenThisWeekController是在主故事板中设计的类。结果,在我的app表中显示没有任何结果。当然,eventThisWeek数组长度不等于0.任何想法我怎么解决它?
答案 0 :(得分:3)
用viewDidLoad替换你的代码。
self.eventStore.requestAccessToEntityType(.Event) {
(granted, error) -> Void in
guard granted else { fatalError("Permission denied") }
let endDate = NSDate(timeIntervalSinceNow: 604800)
let predicate = self.eventStore.predicateForEventsWithStartDate(NSDate(),
endDate: endDate,
calendars: nil)
self.eventsThisWeek = self.eventStore.eventsMatchingPredicate(predicate)
dispatch_async(dispatch_get_main_queue(),{
self.tableView.reloadData()
})
print(self.eventsThisWeek.count)
}
你的cellForRowAtIndexPath
没有调用,因为当你的视图加载时,数组是空的,并且当self.eventStore.requestAccessToEntityType完全执行并且加载具有新值的数组时,你没有通知你的tableView在数组中有新值时重新加载数据。