如何从xml文件中获取与collectionView所选单元格相关的信息,然后打印到tableview?

时间:2018-08-30 05:16:53

标签: ios swift

我已经使用JTAppleCalendar依赖项(它是collectionView)构建了一个日历,并在同一屏幕底部显示了一个tableview。我想在日历中选择一个日期,然后在xml文件中找到该日期,并在tableView中打印其伴随的假日事件。

我正在使用XML解析器来获取日期和假日事件,并且可以解析xml数据并将其打印到控制台。当前,整个xml文件正在tableview中打印,但是我只想打印从calendarView中选择的日期。我对如何使所选日期等于xml日期然后仅将其打印到表格视图中感到困惑,在此步骤上需要一些帮助。

这是我的日历视图控制器的完整代码:

import UIKit
import JTAppleCalendar

class CalendarViewController: UIViewController, XMLParserDelegate {

@IBOutlet weak var calendarView: JTAppleCalendarView!
@IBOutlet weak var year: UILabel!
@IBOutlet weak var month: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var separatorViewTopConstraing: NSLayoutConstraint!

let outsideMonthColor = UIColor.cyan
let monthColor = UIColor.white
let selectedMonthColor = UIColor.darkGray
let currentDateSelectedViewColor = #colorLiteral(red: 0.3647058904, green: 0.06666667014, blue: 0.9686274529, alpha: 1)
let todaysDefaultDateColor  = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
let formatter = DateFormatter()
let todaysDate = Date()
let numOfRowsInCalendar = 6

var tableViewDataSource = [CalendarDates]()
var calendarevent = ""
var monthTableview = ""
var dateTableview = ""
var datenumberTableview = ""
var holidayTableview = ""
var descriptionTableview = ""

override func viewDidLoad() {
    super.viewDidLoad()

    setupCalendarViewAtStart()
    setUpTableViewAtStart()
    setUpBackgroundView()

    self.navigationController?.navigationBar.isTranslucent = true
}

//Mark: Calendar View JTApple code
func setupCalendarViewAtStart(){
    //Scroll to today's date at start
    calendarView.scrollToDate(todaysDate, animateScroll:false)
    calendarView.selectDates([todaysDate])
    //Setup calendar spacing
    calendarView.minimumLineSpacing = 0
    calendarView.minimumInteritemSpacing = 0
    //Setup labels
    self.calendarView.visibleDates { visibleDates in
        self.setupViewsOfCalendar(from: visibleDates)
    }
    self.adjustCalendarViewHeight()
}

func handleCellTextColor(view: JTAppleCell?, cellState: CellState) {
    guard let validCell = view as? CalendarCell else { return }

    if cellState.isSelected {
        validCell.dateLabel.textColor = currentDateSelectedViewColor
    } else {
        if cellState.dateBelongsTo == .thisMonth {
            validCell.dateLabel.textColor = monthColor
        } else {
            validCell.dateLabel.textColor = outsideMonthColor
        }

    validCell.isHidden = cellState.dateBelongsTo == .thisMonth ? false : true
    }
    //today's date selection
    formatter.dateFormat = "yyyy MM dd"
    let todaysDateString = formatter.string(from: todaysDate)
    let monthDateString = formatter.string(from: cellState.date)
    if todaysDateString == monthDateString {
        validCell.dateLabel.textColor = todaysDefaultDateColor
        validCell.dateLabel.font = UIFont.systemFont(ofSize: 30.0)
    } else {
        validCell.dateLabel.textColor = monthColor
        validCell.dateLabel.font = UIFont.systemFont(ofSize: 18.0)
    }
}

func handleCellSelected(view: JTAppleCell?, cellState: CellState) {
    guard let validCell = view as? CalendarCell else { return }
    if validCell.isSelected {
        validCell.selectedView.isHidden = false
    } else {
        validCell.selectedView.isHidden = true
    }
}

func setupViewsOfCalendar(from visibleDates: DateSegmentInfo) {
    let date = visibleDates.monthDates.first!.date
    self.formatter.dateFormat = "yyyy"
    self.year.text = self.formatter.string(from: date)
    self.formatter.dateFormat = "MMMM"
    self.month.text = self.formatter.string(from: date)
}

//Mark: TableView setup
func setUpTableViewAtStart() {
    tableView.dataSource = self
    tableView.delegate = self

    self.tableView.bounces = true

    if let path = Bundle.main.url(forResource: "calendar", withExtension: "xml")
    {
        if let parser = XMLParser(contentsOf: path) {
            parser.delegate = self
            parser.parse()
        }
    }
}
}

//Mark: JTAppleCalendarViewDataSource

extension CalendarViewController: JTAppleCalendarViewDataSource {

func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {
    formatter.dateFormat = "yyyy MM dd"
    formatter.timeZone = Calendar.current.timeZone
    formatter.locale = Calendar.current.locale

    let startDate = formatter.date(from: "2018 08 01")!
    let endDate = formatter.date(from: "2019 01 31")!
    let parameters = ConfigurationParameters(startDate: startDate,
                                             endDate: endDate,
                                             numberOfRows: numOfRowsInCalendar)
    return parameters
}
}

//Mark: JTAppleCalendarViewDelegate

extension CalendarViewController: JTAppleCalendarViewDelegate {
func calendar(_ calendar: JTAppleCalendarView, willDisplay cell: JTAppleCell, forItemAt date: Date, cellState: CellState, indexPath: IndexPath) {

}

//Display the cell
func calendar(_ calendar: JTAppleCalendarView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTAppleCell {
    let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "CalendarCell", for: indexPath) as! CalendarCell

    cell.dateLabel.text = cellState.text

    handleCellSelected(view: cell, cellState: cellState)
    handleCellTextColor(view: cell, cellState: cellState)

    return cell
}

func calendar(_ calendar: JTAppleCalendarView, didSelectDate date: Date, cell: JTAppleCell?, cellState: CellState) {
    handleCellSelected(view: cell, cellState: cellState)
    handleCellTextColor(view: cell, cellState: cellState)
}

func calendar(_ calendar: JTAppleCalendarView, didDeselectDate date: Date, cell: JTAppleCell?, cellState: CellState) {
    handleCellSelected(view: cell, cellState: cellState)
    handleCellTextColor(view: cell, cellState: cellState)
}

}

//Mark: TableView Delegate/DataSource for Date and Holiday Names

extension CalendarViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
   return dateTableview.count
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "\(dateTableview)"
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CalendarDateEvent", for: indexPath)

    let holidayTableviewLabel = cell.viewWithTag(3) as! UILabel
    holidayTableviewLabel.text = tableViewDataSource[indexPath.row].holiday

    let dataTableviewLabel = cell.viewWithTag(2) as! UILabel
    dataTableviewLabel.text = tableViewDataSource[indexPath.row].datenumber

    return cell
}

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    let header = view as! UITableViewHeaderFooterView
    header.textLabel?.font = UIFont.systemFont(ofSize: 16.0)
    header.textLabel?.textColor = #colorLiteral(red: 0.2773199975, green: 0.3366781473, blue: 0.3707436919, alpha: 1)
    header.backgroundView?.backgroundColor = UIColor.white
    tableView.layer.cornerRadius = 20
    tableView.layer.masksToBounds = true

}
}

//Mark: XML Parse Delegate

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

func parser(_ parser: XMLParser, foundCharacters string: String) {

    let data = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)

    if data.count != 0 {
        switch calendarevent
        {
        case "month": monthTableview = data
        case "date": dateTableview = data
        case "datenumber": datenumberTableview = data
        case "holiday": holidayTableview = data
        default: break
        }
    }
}

func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {

    if elementName == "calendarevent"
    {
        var myCalendarDates = CalendarDates()
        myCalendarDates.month = monthTableview
        myCalendarDates.date = dateTableview
        myCalendarDates.datenumber = datenumberTableview
        myCalendarDates.holiday = holidayTableview

        //print(myCalendarDates)
        tableViewDataSource.append(myCalendarDates)
    }
}
}

这是我的Calendar结构:

struct CalendarDates {
var month = ""
var date = ""
var datenumber = ""
    var holiday = ""
    var description = "" }

我的XML文件的结构如下:

< ?xml version="1.0" encoding="UTF-8" ?>
< calendar>
    < calendarmonth id= "August">
        < calendarevent>
            < month>August</month>
            < date>August 20, 2018</date>
            < datenumber>20</datenumber>
            < event>
                < holiday>First Holiday</holiday>
            < /event>
            < event>
                < holiday>Second Holiday</holiday>
            < /event>
        </calendarevent>
        <calendarevent>
            <month>August</month>
            <date>August 26, 2018</date>
            <datenumber>26</datenumber>
            <event>
                <holiday>Third Holiday</holiday>
                <description>ccccccccccc</description>
            </event>
        </calendarevent>
    < /calendarmonth>
< /calendar>

1 个答案:

答案 0 :(得分:1)

您可以按照以下步骤操作:

  

步骤1:在此功能中,您将获得用户从日历中选择的日期。

  var i;    
  for (i=0; i<loc_count; i++){
    (function(j){
       if(loc_count!=0 && loc_count%10==0){
          element(by.css('.publish')).click();
       }
       element(by.cssContainingText("span", loc[j].Location_name)).click();
       console.log(loc[j].Location_name);
       browser.sleep(4000);
       element(by.css('.post')).sendKeys("test"); 
       element(by.css('.submit')).click();
    })(i)
  }
  

第2步:编写逻辑,找出与XML结果匹配的数据。

func calendar(_ calendar: JTAppleCalendarView, didSelectDate date: Date, cell: JTAppleCell?, cellState: CellState) { ... }
  

第3步:重新加载表格,它应该显示所需的结果。

由于您已经为Calendar,TableView编写了逻辑,因此对您来说应该很容易。