简体   繁体   English

通过使用notificationcentre和tableview.reloaddata()无法刷新tableview

[英]tableview not refreshing by using notificationcentre and tableview.reloaddata()

here is the code I use to refresh a tableview when I click a delete button on my custom tableview cell by using notificationcenter and tableview.reloaddata(). 这是当我通过使用Notificationcenter和tableview.reloaddata()在自定义表格视图单元格上单击删除按钮时用来刷新表格视图的代码。 I have searched a bunch of other codes and i think my code looks fine. 我搜索了一堆其他代码,我认为我的代码看起来不错。 I don't know why it just doesn't refresh. 我不知道为什么它不刷新。

This is where my tableview is 这是我的表格视图

override func viewDidLoad() {
    super.viewDidLoad()
    username = tempUser.username
    self.resultSearchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.sizeToFit()
        self.tableView.tableHeaderView = controller.searchBar

        return controller

    })()
    get{(value) in
        self.values = value
        for ele in self.values{
            if self.username != ele["username"] as! String{
            }
        }
    }
    self.tableView.reloadData()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(serviceBoard.methodhandlingTheNotificationEvent), name:"NotificationIdentifie‌​r", object: nil)

}

func methodhandlingTheNotificationEvent(){
    tableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if (self.resultSearchController.active && resultSearchController.searchBar.text != "") {
        return self.filteredTableData.count
    }
    else {
        return values.count
    }
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as!postCell
    let maindata = values[values.count-1-indexPath.row]

    if (self.resultSearchController.active && resultSearchController.searchBar.text != "") {


        //            if (filteredTableData[indexPath.row].rangeOfString("###") == nil){
        cell.postImg.image = UIImage(named:"tile_services")
        cell.title.text = filteredTableData[indexPath.row]
        cell.category.text = "SERVICES"
        var price = String()
        for i in values{
            if (i["title"] as? String)! == filteredTableData[indexPath.row]{
                price = (i["price"] as? String)!
                cell.categories = "Services"
                cell.username = i["username"] as! String
                cell.prices = i["price"] as! String
                cell.notes = i["notes"] as! String
                cell.school = i["school"] as! String
            }
        }
        cell.price.text = price 

        return cell
    }
    else {
        if maindata["username"] as! String != username && username != "admin"{
            cell.deleteBtn.hidden = true
        }
        else{
            cell.categories = "Services"
            cell.username = maindata["username"] as! String
            cell.prices = maindata["price"] as! String
            cell.notes = maindata["notes"] as! String
            cell.school = maindata["school"] as! String
        }

        cell.postImg.image = UIImage(named:"tile_services")
        cell.title.text = maindata["title"] as? String
        cell.category.text = "SERVICES"
        cell.price.text = maindata["price"] as? String

        return cell
    }
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("showPostT") as! showPostT
    self.addChildViewController(popOverVC)
    popOverVC.view.frame = self.view.frame
    self.view.addSubview(popOverVC.view)
    popOverVC.didMoveToParentViewController(self)
    if (self.resultSearchController.active && resultSearchController.searchBar.text != "") {
        for i in values{
            if (i["title"] as? String)! == filteredTableData[indexPath.row]{
                popOverVC.type.text = "SERVICE"
                popOverVC.typeImg.image = UIImage(named:"tile_services")
                popOverVC.item.text = "Service: \(i["title"] as! String)"
                popOverVC.price.text = "Price: \(i["price"] as! String)"
                popOverVC.notes.text = "Notes: \(i["notes"] as! String)"
                popOverVC.comments.text = i["comments"] as? String
                popOverVC.postUser.text = i["username"] as! String
                popOverVC.notesStr = i["notes"] as! String
                popOverVC.category = "service"
                popOverVC.pricesStr = i["price"] as! String
                if username == popOverVC.postUser.text!{
                    popOverVC.composeBtn.hidden = true
                }
            }
        }
    }
    else{
        let maindata = values[values.count-1-indexPath.row]
        popOverVC.type.text = "SERVICE"
        popOverVC.typeImg.image = UIImage(named:"tile_services")
        popOverVC.item.text = "Service: \(maindata["title"] as! String)"
        popOverVC.price.text = "Price: \(maindata["price"] as! String)"
        popOverVC.notes.text = "Notes: \(maindata["notes"] as! String)"
        popOverVC.comments.text = maindata["comments"] as? String
        popOverVC.postUser.text = maindata["username"] as! String
        popOverVC.notesStr = maindata["notes"] as! String
        popOverVC.category = "service"
        popOverVC.pricesStr = maindata["price"] as! String

        if username == popOverVC.postUser.text!{
            popOverVC.composeBtn.hidden = true
        }
    }

}

and this is my custom tableview cell 这是我自定义的tableview单元格

class postCell: UITableViewCell{

@IBOutlet weak var deleteBtn: UIButton!
@IBOutlet weak var postImg: UIImageView!
@IBOutlet weak var category: UILabel!
@IBOutlet weak var location: UILabel!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var price: UILabel!
var prices = String()
var notes = String()
var comments = String()
var locations = String()
var categories = String()
var school = String()
var username = String()
var date = String()


@IBAction func deleteAction(sender: AnyObject) {
    let request = NSMutableURLRequest(URL: NSURL(string: "http://www.percyteng.com/orbit/deletePost.php")!)
    request.HTTPMethod = "POST"
    let postString = "name=\(username)&location=\(locations)&price=\(prices)&notes=\(notes)&school=\(school)&category=\(categories)"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            print("error=\(error)")
            return
        }

        print("response = \(response)")

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")
    }
    task.resume();           NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifie‌​r", object: nil)


}

override func awakeFromNib() {
    super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated:animated)
}
}

尝试在viewDidAppear()中重新加载表。

It looks like you are not updating the values property when you click on the "Delete" button. 当您单击“删除”按钮时,您似乎没有更新values属性。

func methodhandlingTheNotificationEvent(){
    // you have to update the `values` array so that it doesn't contain the value you've just removed.
    tableView.reloadData()
}

You have to update your data source before reloading tableview then only your tableview will affected otherwise you will always got old table. 您必须在重新加载tableview之前更新数据源,然后只有您的tableview才会受影响,否则您将始终获得旧表。

I think maindata is main datasource in your cellforrowAtIndexpath . 我认为maindata是在主数据源cellforrowAtIndexpath So you have to update or delete from your datasource and then you should reload data. 因此,您必须更新或从数据源中删除,然后应该重新加载数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM