删除tableview单元格后刷新tableview并刷新视图控制器

时间:2016-07-18 12:15:44

标签: ios swift uitableview uiviewcontroller refresh

顺便说一句,我需要快速回答。基本上,我有两个问题需要提神。如果您认为代码太长而无法查看,那么这就是我想要做的。一种是在点击其中一个tableview单元格上的删除按钮后刷新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)
}
}

而tableview我想重新加载另一个类的数据:

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
        }
    }

}

我不认为我需要第二个问题的代码,我只是想知道如何刷新视图控制器。我试图关闭当前的控制器并重新打开它,但它显然不起作用。

如果你们能帮助解决任何问题我真的很感激!

谢谢!

2 个答案:

答案 0 :(得分:2)

嗯,首先,如果要刷新tableview数据,必须通知它,因此它知道模型中是否有任何更改。 如果你想重新加载整个表视图(我强烈建议不要这样做) 你可以用

 tableView.reloadData()

如果要刷新某些行,请使用以下方法:

tableView.reloadRowsAtIndexPaths(paths, withRowAnimation: UITableViewRowAnimation.None) 

或者您只能将此方法用于删除操作。观察点击按钮事件并将信号发送到tableView以删除该行。当tableView接收到这个信号时,只需执行以下方法。

 tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

强制重绘自定义视图:view.setNeedsDisplay()

答案 1 :(得分:0)

重新加载tableview数据

[_ tableView reloadData];