按组排序数据

时间:2017-04-17 01:27:45

标签: ios swift xcode core-data

以下是我界面的外观,如果我创建一个事件,它是黑色的,一旦我从动作控制器中选择是或否,它会相应变为绿色或红色。

如果我在行中选择了一个事件并选择了yes,则会转为green,我希望在Yes section下对其进行排序,如果no转为red我希望在No section下对其进行排序。但我无法做到这一点,因为我创建的所有事件都被归为Events section。我想知道如何在他们所属的部分下发送事件。

例如,我喜欢按群组对事件进行排序,我希望English101下的YesMath101以及No下的Geo 101 , Stats 101Events下。我尝试了很多,以便在我的代码中的不同位置填充OncYesOncNo数天徒劳无功。

enter image description here

var eventTitleOnc:[String] = []
    var oncYes:[String] = []
    var oncNo:[String] = []
    var oncEventsPresent: [String] = []
    var eventType:[Int] = []
    var oncEvents : [String] = []
var eventScheduleOnc = [EventScheduleOnc]()
let sectionTitles:[String] = ["Events","Yes","No"]

  override func viewDidLoad() {
    super.viewDidLoad()
       eventDataOnc()
        for i in stride(from: 0, to: eventTitleOnc.count, by: 1){
                oncEventsPresent.append(eventTitleOnc[i])
            }
        myEventTableView.reloadData()
    }

// Number of Rows in Section

 public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        var typeOfEvent = 0

        if(section == 0)
        {
         typeOfEvent = oncEventsPresent.count
        }
        if(section == 1)
        {
            typeOfEvent = oncYes.count
        }
        if(section == 2)
        {
            typeOfEvent = oncNo.count
        }
    return typeOfEvent
}

// Cell for Row
 public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let myEventCell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! EventTableViewCell
        myEventCell.eventLabel.text = self.eventScheduleOnc[indexPath.row].eventNameOnc
        let eventDesc = self.eventScheduleOnc[indexPath.row].eventDecOnc
        let eventStatus = eventDesc?.eventStatus
           if eventStatus == 1 {
                myEventCell.eventLabel.textColor = UIColor.green
            }
            else if eventStatus == 2{
                myEventCell.eventLabel.textColor = UIColor.red
            }
        else
           {
            myEventCell.eventLabel.textColor = UIColor.black
            }
          }
           return myEventCell
    }


//Did Select Row at index path

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
    let eventDesc = NSEntityDescription.insertNewObject(forEntityName: "EventDec", into: context) as! EventDec
    var eventSchOnc :EventScheduleOnc?
    do {
            let fetchRequestOnc:NSFetchRequest<EventScheduleOnc> = EventScheduleOnc.fetchRequest()
            fetchRequestOnc.returnsObjectsAsFaults = false
             fetchRequestOnc.predicate = NSPredicate(format: "eventNameOnc == %@",self.oncEventsPresent[indexPath.row] as String )
             var eventSchOncObjects = [EventScheduleOnc]()
             try eventSchOncObjects = context.fetch(fetchRequestOnc)
             eventSchOnc = eventSchOncObjects[0] as EventScheduleOnc
            }
catch {}
    eventDesc.setValue(eventSchOnc, forKey: "eventScheduleOnc")
    let alert = UIAlertController(title: "title", message: "msg", preferredStyle: .alert)
    DispatchQueue.main.async {
    alert.addAction(UIAlertAction(title: "yes", style: .default ){ _ in
        eventDesc.setValue(1, forKey: "eventStatus")
        do {
            try context.save()
            self.myEventTableView.reloadData()
           }
        catch{}
    })
    alert.addAction(UIAlertAction(title: "no", style: .default) { _ in
        eventDesc.setValue(2, forKey: "eventStatus")

        do{
            try context.save()
            self.myEventTableView.reloadData()
          }
        catch {}
    })
  }
present(alert, animated: true, completion: nil)
}

//MARK: - Core data

private func eventDataOnc(){
    let eventsOncFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"EventScheduleOnc")
    let primarySortDescriptor = NSSortDescriptor(key:"eventDecOnc.eventStatus", ascending: false)
    let secondarySortDescriptor = NSSortDescriptor(key:"eventNameOnc", ascending: true)
    eventsOncFetchRequest.sortDescriptors = [primarySortDescriptor,secondarySortDescriptor]
do
    {
        let results = try context.fetch(eventsOncFetchRequest)
        if results.count > 0
        {
            for result in results
            {
                if let eventDisTextOnc = (result as AnyObject).value(forKey: "eventNameOnc") as? String
                {
                        eventTitleOnc.append(eventDisTextOnc)
                }
            }
        }
            self.eventScheduleOnc = try context.fetch(eventsOncFetchRequest) as! [EventScheduleOnc]
    }
    catch{print(error.localizedDescription)}
}

如何按组对此数据进行排序?

1 个答案:

答案 0 :(得分:0)

我会使用包含3个部分的tableview:

enum Section { 
     case undecided, yes, no 
     static let all: [Section] = [.undecided, .yes, .no]
}

然后我会将我的数据粘贴到数组字典中(或者是具有相关值的枚举数组):

var events[Section: [String]] = [.undecided: [], .yes: [], .no: []]

您的数据源方法如下所示:

    extension V: UITableViewDataSource {
        func numberOfSections(in tableView: UITableView) -> Int {
            return Sections.all.count
        }
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return events[Sections.all[section]]!.count
        }
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: MyCell.self), for: indexPath) as MyCell
            cell.event = events[Sections.all[section]]!
            return cell
        }
    }