如何在我的应用程序中一次重置所有任务?

时间:2015-11-30 23:13:16

标签: swift parse-platform

我使用Swift和Parse创建了一个todo应用程序。我试图给出一个重置按钮功能,但我不知道从哪里开始。我的代码如下。

在代码中途,我有一个IBAction。

// Reset all tasks to uncompleted state
        @IBAction func resetTasks(sender: UIBarButtonItem) {

        }

我不想重置整个应用中的每个任务。我想重置该特定部分中的任务(在应用程序中称为“团队”)。我是否使用for循环来遍历任务数组?如果是这样,我如何使用PFObjects做到这一点?

import UIKit
import Parse

protocol TaskCellDelegate {
    func doneHit(cell : TaskCell)
}

class TaskCell : UITableViewCell {

    var delegate : TaskCellDelegate?

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var checkBox: CheckBox!
    @IBOutlet weak var detailLabel: UILabel!


    override func awakeFromNib() {
        super.awakeFromNib()
        checkBox.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
    }


    func buttonClicked(sender:UIButton) {
        delegate?.doneHit(self)

    }

}


class CheckBox: UIButton {

    //images
    let checkedImage = UIImage(named: "checkedbox")
    let unCheckedImage = UIImage(named: "uncheckedbox")


    //bool propety
    var isChecked:Bool = false{
        didSet {
            if isChecked == true{
                self.setImage(checkedImage, forState: .Normal)
            }
            else {
                self.setImage(unCheckedImage, forState: .Normal)
            }
        }
    }


    override func awakeFromNib() {
        self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
    }



    func buttonClicked(sender:UIButton) {
        if(sender == self){
            if isChecked == false {
                isChecked = true
            } else {
                isChecked = false
            }
        }
    }


}

class AdminTasksTVC: UITableViewController, TaskCellDelegate {


    override func viewWillAppear(animated: Bool) {
        if (PFUser.currentUser() == nil) {
            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                let viewController:UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("Login")
                self.presentViewController(viewController, animated: true, completion: nil)
            })
        }
    }

    var checked = CheckBox()
    var user = ""
    var team = ""
    var tasks = [PFObject]() {
        didSet {
            tableView?.reloadData()
        }
}




    @IBAction func addBarButtonTapped(sender: UIBarButtonItem) {
        let ac = UIAlertController(title: "Add Task", message: nil, preferredStyle: .Alert)
        ac.addTextFieldWithConfigurationHandler() {textField in
            textField.placeholder = "Task"
        }
        ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
        ac.addAction(UIAlertAction(title: "Post", style: .Default, handler: {action in
            if let task = ac.textFields?[0].text {
                if task.characters.count == 0 {
                    UIAlertView(title: "Add a task", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
                    return
                }
                let obj = PFObject(className: "Tasks")
                obj.setValue(task, forKey: "task")
                obj.setValue(self.team, forKey: "team")
                obj.setValue(self.checked.isChecked, forKey: "done")
                obj.setValue(self.user, forKey: "completedBy")
                obj.saveInBackgroundWithBlock() {success,error in
                    if error != nil {
                        print(error)
                        return
                    }
                    if success {
                        self.loadTasks()
                    }
                }
            }
        }))

        presentViewController(ac, animated: true, completion: nil)
    }

    func loadTasks() {
        let query = PFQuery(className: "Tasks")
        query.whereKey("team", equalTo: team)
        query.findObjectsInBackgroundWithBlock { (objects, error : NSError?) -> Void in
            if let objects = objects {
                self.tasks = objects

            }
        }

        self.refreshControl?.endRefreshing()
    }


// Reset all tasks to uncompleted state
    @IBAction func resetTasks(sender: UIBarButtonItem) {

    }



    func loginType() {
        if let user = PFUser.currentUser() {
            print("\(user)")
            let type = user.objectForKey("type") as! String
            print("\(type)")

            if type == "admin" {
                self.navigationItem.rightBarButtonItem = self.editButtonItem()
            }

        } }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.

        loginType()


        let refreshControl = UIRefreshControl()
        refreshControl.attributedTitle = NSAttributedString(string: "Pull to Refresh")
        refreshControl.addTarget(self, action: Selector("loadTasks"), forControlEvents: UIControlEvents.ValueChanged)
        self.refreshControl = refreshControl


        tableView?.rowHeight = UITableViewAutomaticDimension
        tableView?.estimatedRowHeight = 44
        loadTasks()


    }

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

    // MARK: - TaskCellDelegate

    func doneHit(cell:TaskCell) {
        if let ip = tableView.indexPathForCell(cell) {
            let task = tasks[ip.row]
            let query = PFQuery(className: "Tasks")
            query.getObjectInBackgroundWithId(task.objectId!) { (object, error) -> Void in
                if error != nil {
                    print(error)
                }
                else if let object = object {
                    object["done"] = cell.checkBox.isChecked
                    print(cell.checkBox.isChecked)
                    if cell.checkBox.isChecked == true {
                        object["completedBy"] = "Completed by: \(PFUser.currentUser()!.email!)"
                    }
                    else {
                        object["completedBy"] = ""
                    }
                    object.saveInBackground()
                    self.tasks[ip.row] = object
                }
            }
        }
    }



            /*
            task.setValue(cell.checkBox.isChecked, forKey:"done")
            task.saveInBackgroundWithBlock() {success,error in
                if error != nil {
                    print(error)
                    return
                }
                if success {
                    //self.tableView.reloadData()
                }
            }
        */



    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

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


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath) as! TaskCell

        // Configure the cell...
        cell.selectionStyle = .None
        let idx = tasks[indexPath.row]
        let task = idx["task"] as! String
        if let label = cell.viewWithTag(1) as? UILabel {
            label.text = task
        }

        let done = idx["done"] as! Bool
        if let checkBox = cell.viewWithTag(2) as? CheckBox {
            checkBox.isChecked = done
        }


        let completedBy = idx["completedBy"] as? String
        if let userCompleted = cell.viewWithTag(3) as? UILabel {
            userCompleted.text = completedBy
        }

        cell.delegate = self

        return cell
    }


    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */


    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

        if editingStyle == .Delete {
            if let user = PFUser.currentUser() {
                print("\(user)")
                let type = user.objectForKey("type") as! String
                print("\(type)")

                if type == "admin" {
                    // Delete the row from the data source
                    tasks[indexPath.row].deleteInBackgroundWithBlock({ (success, error) -> Void in
                        if error != nil {
                            print(error)
                            return
                        }
                        if success {
                            tableView.beginUpdates()
                            self.tasks.removeAtIndex(indexPath.row)
                            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
                            tableView.endUpdates()
                        }
                    })
                    self.loadTasks()
                }
            }
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }
    }

任何和所有帮助都非常有用。谢谢!

1 个答案:

答案 0 :(得分:1)

任务是一个PFObject数组,所以你对for循环的想法可以正常工作,一旦它按照你的意愿填充,就可以遍历该集合......

// Reset all tasks to uncompleted state
@IBAction func resetTasks(sender: UIBarButtonItem) {

    for task in tasks {
        //do whatever you'd like here to each piece (task) of tasks
        task.doWhateverToEachTask
    }
}

关于For循环的Apple文档: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-ID121