gpt4 book ai didi

swift - 如何在待办事项应用程序中一次性重置所有任务?

转载 作者:行者123 更新时间:2023-11-30 10:09:13 25 4
gpt4 key购买 nike

我使用 Swift 和 Parse 创建了一个待办事项应用程序。我正在尝试提供重置按钮功能,但我不知道从哪里开始。我的代码如下。

代码中途我有一个 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
}
}

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

最佳答案

Tasks 是一个 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

关于swift - 如何在待办事项应用程序中一次性重置所有任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34009763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com