TableView在重新加载时显示重复的单元格

时间:2015-08-07 00:27:22

标签: ios swift uitableview amazon-web-services tableviewcell

我想显示与tableView中的datePicker中选择的特定日期相关的数据。但是,当我重新加载tableView时,它显示重复的单元格。这是我的代码

sessionViewController.swift

import UIKit
class sessionViewController: UIViewController{

@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var datePicker: UIDatePicker!

override func viewDidLoad() {
super.viewDidLoad()
    datePicker.datePickerMode = UIDatePickerMode.Date
    datePicker.addTarget(self, action: Selector("datePickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)

    let date = NSDate()
    let formatter = NSDateFormatter()
    formatter.dateFormat = "M/d/yyyy"

    let today = formatter.stringFromDate(date)
    dateLabel.text = today


}

func datePickerChanged(datePicker:UIDatePicker) {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "M/d/yyyy"


    var strDate = dateFormatter.stringFromDate(datePicker.date)
    dateLabel.text = strDate
    Singelton.setTutorDate(strDate)
    NSNotificationCenter.defaultCenter().postNotificationName("load", object: nil)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

sessionTableViewController.swift     导入UIKit

class sessionTableViewController: UITableViewController{
var myData: Array<tutor> = []
var myDummy: Array<String> = []
var date: String!

override func viewDidLoad() {
    super.viewDidLoad()
    println("\(myData)")

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "loadList:",name:"load", object: nil)

    date = Singelton.getTutorDate()
    myDummy = ["Harsh","Akash","A","B","C","d","e","f","g","h","i","j","k","l","m","n"]
    let cond = AWSDynamoDBCondition()
    let v1    = AWSDynamoDBAttributeValue(); v1.S = date
    cond.comparisonOperator = AWSDynamoDBComparisonOperator.EQ
    cond.attributeValueList = [ v1 ]



    let exp = AWSDynamoDBScanExpression()
    exp.scanFilter = [ "startDate" : cond ]


    self.scan(exp).continueWithSuccessBlock({ (task: AWSTask!) -> AWSTask! in
        NSLog("Scan multiple values - success")
        let results = task.result as! AWSDynamoDBPaginatedOutput
        for r in results.items {


            let myItem: secondItem = r as! secondItem

            let myTutor: tutor = tutor()

            myTutor.setName(myItem.name)
            myTutor.seteMail(myItem.email)
            myTutor.setStartDate(myItem.startDate)
            myTutor.setStartTime(myItem.startTime)
            myTutor.setEndTime(myItem.endTime)
            println(myItem.name)

            self.myData.append(myTutor)
            println("\(self.myData)")

        }
        dispatch_async(dispatch_get_main_queue(), {
            self.tableView.reloadData()
        });
        return nil
    })
}

func loadList(notification: NSNotification){
    //load data here
   // myData.removeAll(keepCapacity: false)
    self.myData.removeAll(keepCapacity: false)
    self.viewDidLoad()
}



func scan(expression : AWSDynamoDBScanExpression) -> AWSTask! {

    let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()
    return mapper.scan(secondItem.self, expression: expression)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return myData.count

}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cellID: String = "cell1"
    var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! timeCell

 //   cell.separatorInset = UIEdgeInsetsZero
//    cell.nameTutor.text = self.myData[indexPath.row].getName() as String
    cell.nameTutor.text = self.myData[indexPath.row].getName() as String
    cell.timeLabel.text = self.myData[indexPath.row].getstartDate() as String
    cell.hourLabel.text = "\(self.myData[indexPath.row].getStartTime())-\(self.myData[indexPath.row].getendTime())"
    return cell
}



override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let indexPath = tableView.indexPathForSelectedRow();
    println("\(indexPath?.row)")


}

以下是截图。当我从datePicker更改日期时,tableView会重新加载,但是单元格会重复。

如果有人可以建议我出路,那将是一个很大的帮助。谢谢  }

enter image description here

1 个答案:

答案 0 :(得分:1)

您不应该手动调用ViewDidLoad。让框架调用View Lifecycle事件。

将填充myData数组的代码移动到单独的方法中。从ViewDidLoad调用此方法代替当前逻辑。然后在loadData method中再次调用此方法以重新填充列表并重新加载表数据。