当每个节中的行数变化时,如何获取numberOfRows的计数?

时间:2018-10-03 01:45:49

标签: ios swift uitableview

我正在尝试使用XML文件中的条目填充表格视图。到目前为止,我已经将XML文件解析为Struct并编写了titleForHeaderInSection和numberOfSections的方法,但是我正在努力通过计算每个<holiday>中的<calendarevent>项来计算每个节的numberOfRows。我认为我的主要努力来自于不了解如何使用[section]。到目前为止,这是我所做的:

我已经解析了一个具有日历日期和事件的xml文件。您将看到第一个日历事件如何具有2个假日和描述条目,而第二个事件如何具有1.:

<calendar>
    <calendarevent>
        <month>October</month>
        <dateevent>2018 10 01</dateevent>
        <datenumber>01</datenumber>

        <holiday>First Holiday</holiday>
        <description>aaaaaaaaaa</description>

        <holiday>Second Holiday</holiday>
        <description>bbbbbbbbbb</description>

    </calendarevent>
    <calendarevent>
        <month>October</month>
        <dateevent>2018 10 10</dateevent>
        <datenumber>10</datenumber>

        <holiday>Third Holiday</holiday>
        <description>ccccccccccc</description>

    </calendarevent>
    .... and so on

对于这样的结构:

struct CalendarDates {
    struct CalendarEvents {
        var month = ""
        var eventdate = ""
        var eventdatenumber = ""
        var holiday = ""
        var description = ""
        }
}

这是我的XML解析器代码:

class CalendarViewController {
    var myCalendarDatesFromStrut = [CalendarDates]()
    var myCalendarEventsFromStrut = [CalendarDates.CalendarEvents]()
}

extension CalendarViewController {
    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
        calendarEventsElementFromXML = elementName
    }

    func parser(_ parser: XMLParser, foundCharacters string: String) {
        let data = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        if data.count != 0 {
            switch calendarEventsElementFromXML
            {
            case "month": monthsFromXML = data
            case "dateevent": eventdatesFromXML = data
            case "datenumber": eventdatenumbersFromXML = data
            case "holiday": holidaysFromXML = data
            default: break
            }
        }
    }

    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        if elementName == "calendarevent" {
            var myCalendarDates = CalendarDates.CalendarEvents()
            myCalendarDates.month = monthsFromXML
            myCalendarDates.eventdate = eventdatesFromXML
            myCalendarDates.eventdatenumber = eventdatenumbersFromXML
            myCalendarDates.holiday = holidaysFromXML
            myCalendarEventsFromStrut.append(myCalendarDates)
        }
    }
}

因此,在解析XML并将其附加到结构之后,我开始获取tableview的值。

如果<calendarevent>与当前日期月份相同,则每个部分都由一个<month>组成。 XML具有其他月份的<calendarevent>,所以我不希望所有这些。我检查当前月份是否为XML中的==月,如果是,则将numberofSections计数为numberOfSections,并将dateevents格式化为这些部分的标题。

然后,节中的每一行代表相应的<holiday>中的一个<calendarevent>

extension CalendarViewController: UITableViewDelegate, UITableViewDataSource {
    //Calculates # of <dateevents> in current month
    func numberOfSections(in tableView: UITableView) -> Int {
        formatter.dateFormat = "MMMM"
    let currentMonthShown = formatter.string(from: selectedDate)
    let allEventsInVisibleMonth = myCalendarEventsFromStrut.filter({ $0.month == currentMonthShown }).map {$0.eventdate}.count
    return allEventsInVisibleMonth
    }

    // Prints <dateevent> reformatted as section header
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        formatter.dateFormat = "MMMM"
    let currentMonthShown = formatter.string(from: selectedDate)
    let allEventsInVisibleMonth = myCalendarEventsFromStrut.filter({ $0.month == currentMonthShown }).map {$0.eventdate}
    formatter.dateFormat = "yyyy-MM-dd"
    let eventStringsToDate = allEventsInVisibleMonth.map{ formatter.date(from: $0) }
    formatter.dateFormat = "yyyy-MM-dd"
    formatter.dateStyle = .long
    formatter.timeStyle = .none
    let eventDatesBackToString = eventStringsToDate.map{ formatter.string(from: $0 as! Date )}
    return eventDatesBackToString[section]
    }

现在,节中的每一行都需要在相应的<holiday>中代表一个<calendarevent>-这就是我遇到的问题。

对于表视图的numberOfRowsInSection,我需要计算每个<holiday>中的<calendarevent>个条目中的#个,并在每个节中显示#行。然后在cellForRowAt中打印。有人可以给我提示这里的逻辑吗?

这是我尝试过的方法,也是我失败的地方:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     formatter.dateFormat = "MMMM"
     let currentMonthShown = formatter.string(from: selectedDate)
    let allEventsInMonth = myCalendarEventsFromStrut.filter({ $0.month == currentMonthShown }).map {$0.holiday}

    return allEventsInMonth.count //This gets me same number of rows in all sections = total # of events in current month.

//I'm struggling to figure out how to get # of events at a particular section, so I can make that the # of rows
    }

1 个答案:

答案 0 :(得分:1)

首先,XML可能在单个holiday中包含多个calendarevent元素,因此您需要更新CalendarEvents才能容纳多个假期。

struct Holiday {
    var title: String = ""
    var description: String = ""
}

//You should better avoid plural form for something which represents a single object
struct CalendarEvent {
    var month: String = ""
    var eventdate: String = ""
    var eventdatenumber: String = ""
    //Better use plural form for the name representing multiple objects
    var holidays: [Holiday] = []
}

(我删除了外部结构CalendarDates,因为找不到任何需要嵌套类型的原因。此外,我建议您避免使用复数形式来命名代表单个对象的东西。)


要使用结构解析XML,您需要在XMLParserDelegate中使用更多属性:

class CalendarViewController: UIViewController {
    //`myCalendarEventsFromStrut` is too long and `FromStrut` does not make sense
    var myCalendarEvents: [CalendarEvent] = []

    //Properties needed for parsing your XML
    var textCurrentlyParsed: String? = nil
    var monthFromXML: String = ""
    var dateeventFromXML: String = ""
    var datenumberFromXML: String = ""
    var holidaysFromXML: [Holiday] = []

    //Your table view shows some selected evnets in `myCalendarEvents`,
    //To improve response, you should beter keep the filtered result, when `selectedDate` is updated.
    var selectedDate: Date? {
        didSet {
            if let date = selectedDate {
                let currentMonthShown = monthFormatter.string(from: date)
                allEventsInVisibleMonth = myCalendarEvents.filter({ $0.month == currentMonthShown })
            } else {
                allEventsInVisibleMonth = [] //Or you prefer `allEventsInVisibleMonth = myCalendarEvents`?
            }
        }
    }
    var allEventsInVisibleMonth: [CalendarEvent] = []

    //You may have this sort of constants somewhere, this is just an example
    let TheCellID = "cell" //Change this according to your actual setups

    //
    // Date formatters.
    //  Better keep distinct DateFormaters accoding to the format to avoid simple mistakes
    //

    let monthFormatter: DateFormatter = {
       let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "MMMM"
        return formatter
    }()

    let dateeventFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy MM dd"
        return formatter
    }()

    let sectionHeaderFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter
    }()

    //...
}

(上面的代码进行了一些补充,以编写UITableViewDataSource方法的示例。)

使用上面的属性,您可以编写XMLParserDelegate方法,如下所示:

extension CalendarViewController: XMLParserDelegate {
    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
        switch elementName {
        case "month", "dateevent", "datenumber", "holiday", "description":
            //Reset the text content for the element
            textCurrentlyParsed = ""
        case "calendarevent":
            //Reset all variables which may contain the result of previous element
            monthFromXML = ""
            dateeventFromXML = ""
            datenumberFromXML = ""
            holidaysFromXML = []
        case "calendar":
            //Can be ignored
            break
        default:
            print("Unexpected start tag:", elementName)
            break
        }
    }

    func parser(_ parser: XMLParser, foundCharacters string: String) {
        //`parser(_:foundCharacters:)` may be called several times for a seemingly single text content,
        //So you need to add the `string` to the currently parsed text
        textCurrentlyParsed? += string
    }

    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        switch elementName {
        case "calendarevent":
            var calendarEvent = CalendarEvent()
            calendarEvent.month = monthFromXML
            calendarEvent.eventdate = dateeventFromXML
            calendarEvent.eventdatenumber = datenumberFromXML
            calendarEvent.holidays = holidaysFromXML
            myCalendarEvents.append(calendarEvent)
        case "month":
            if let parsedText = textCurrentlyParsed?.trimmingCharacters(in: .whitespacesAndNewlines) {
                monthFromXML = parsedText
            }
        case "dateevent":
            if let parsedText = textCurrentlyParsed?.trimmingCharacters(in: .whitespacesAndNewlines) {
                dateeventFromXML = parsedText
            }
        case "datenumber":
            if let parsedText = textCurrentlyParsed?.trimmingCharacters(in: .whitespacesAndNewlines) {
                datenumberFromXML = parsedText
            }
        case "holiday":
            if let parsedText = textCurrentlyParsed?.trimmingCharacters(in: .whitespacesAndNewlines) {
                var holiday = Holiday()
                holiday.title = parsedText
                holidaysFromXML.append(holiday)
            }
            break
        case "description":
            if
                let parsedText = textCurrentlyParsed?.trimmingCharacters(in: .whitespacesAndNewlines),
                case let lastIndexOfHoliday = holidaysFromXML.count - 1, lastIndexOfHoliday >= 0
            {
                //You need to modify the last entry in `holidaysFromXML`
                holidaysFromXML[lastIndexOfHoliday].description = parsedText
            }
        default:
            print("Unexpected end tag:", elementName)
            break
        }
    }
}

(如果您不需要trim这些文本,可以将上面的代码简化一些。)


包含这些代码后,您的UITableViewDataSource方法将如下所示:

extension CalendarViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return allEventsInVisibleMonth.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return allEventsInVisibleMonth[section].holidays.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let eventForTheSection = allEventsInVisibleMonth[indexPath.section]
        let holidayForTheRow = eventForTheSection.holidays[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: TheCellID, for: indexPath)
        //... setup the cell using `eventForTheSection` and `holidayForTheRow`
        return cell
    }

    // Prints <dateevent> reformatted as section header
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let eventForTheSection = allEventsInVisibleMonth[section]
        if let eventdateAsDate = dateeventFormatter.date(from: eventForTheSection.eventdate) {
            return sectionHeaderFormatter.string(from: eventdateAsDate)
        } else {
            return "Broken eventdate: \(eventForTheSection.eventdate)"
        }
    }

}

(未经测试,您可能需要一些修复。)

通常,UITableViewDataSource方法可以经常调用,因此您应该有效地实现它们。

因此,不建议在每次调用时创建一个过滤数组。 您最好仅在以下情况下更新allEventsInVisibleMonth

  • myCalendarEvents已更新(上面的代码中未包含)
  • selectedDate已更新(didSet中的selectedDate会做到)

有点长,但是我认为值得尝试。