简体   繁体   English

Swift:在点击时在表格视图中更改按钮图像

[英]Swift: Change button image in table view on click

I created an Xcode project for iPhone using Swift, with Parse for the backend. 我使用Swift创建了一个iPhone的Xcode项目,后端使用了Parse。 My current problem is with creating a todo list application as one tab of a larger application. 我当前的问题是将待办事项列表应用程序创建为较大应用程序的一个选项卡。

Inside of a custom prototype cell, I want to have a checkbox button that changes its image when clicked as well as changing the isChecked:Bool variable for that cell. 在自定义原型单元内,我想有一个复选框按钮,该按钮可以在单击时更改其图像,以及更改该单元的isChecked:Bool变量。 I've gotten most of the way there, but I've run into a brick wall regarding setting and accessing the appropriate variables for this button. 我已经完成了大部分工作,但是在设置和访问此按钮的适当变量方面遇到了麻烦。

Edit: Thanks to the answer below and other resources, I have finally written working code for this checkbox functionality. 编辑:由于下面的答案和其他资源,我终于为此复选框功能编写了工作代码。 Essentially, the button's tag property is set equal to the indexPath.row of the PFObject. 本质上,按钮的tag属性设置为等于PFObject的indexPath.row。 As my original question was a bit broad, I am updating my code below so that it might help other new developers who are working on similar functionality. 由于我最初的问题有点宽泛,因此我在下面更新我的代码,以便它可以帮助从事类似功能的其他新开发人员。 There may be better ways, but this seems to work. 也许有更好的方法,但这似乎可行。

// TasksVC.swift // TasksVC.swift

var taskObjects:NSMutableArray! = NSMutableArray()

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)    
    self.fetchAllObjects()
}

func fetchAllObjects() {

    var query:PFQuery = PFQuery(className: "Task")

    query.whereKey("username", equalTo: PFUser.currentUser()!)

    query.orderByAscending("dueDate")
    query.addAscendingOrder("desc")

    //fetches values within pointer object
    query.includeKey("deal")

    query.findObjectsInBackgroundWithBlock { (tasks: [AnyObject]!, error:NSError!) -> Void in

        if (error == nil) {

            var temp:NSArray = tasks! as NSArray
            self.taskObjects = temp.mutableCopy() as NSMutableArray

            self.tableView.reloadData()

            println("Fetched objects from server")

        } else {
            println(error?.userInfo)
        }
    }
}


//MARK: - Tasks table view
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.taskObjects.count
}

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

    var dateFormatter:NSDateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "M/dd/yy"

    var task:PFObject = self.taskObjects.objectAtIndex(indexPath.row) as PFObject

    cell.desc_Lbl?.text = task["desc"] as? String
    cell.date_Lbl.text = dateFormatter.stringFromDate(task["dueDate"] as NSDate)

    //value of client within Deal pointer object
    if let deal = task["deal"] as? PFObject {
        // deal column has data
        if let client = deal["client"] as? String {
            // client has data
            cell.client_Lbl?.text = client
        }
    }

    //set the tag for the cell's UIButton equal to the indexPath of the cell
    cell.checkbox_Btn.tag = indexPath.row
    cell.checkbox_Btn.addTarget(self, action: "checkCheckbox:", forControlEvents: UIControlEvents.TouchUpInside)
    cell.checkbox_Btn.selected = task["isCompleted"] as Bool

    if (task["isCompleted"] != nil) {
            cell.checkbox_Btn.setBackgroundImage(UIImage(named:(cell.checkbox_Btn.selected ? "CheckedCheckbox" : "UncheckedCheckbox")), forState:UIControlState.Normal)
    }

    cell.selectionStyle = .None

    return cell

}

func checkCheckbox(sender:UIButton!) {
    var senderBtn:UIButton = sender as UIButton
        println("current row: \(senderBtn.tag)")

    //retrieve the PFObject for the row we have selected
    var task:PFObject = self.taskObjects.objectAtIndex(senderBtn.tag) as PFObject
        println("objectID: \(task.objectId)")

    if task["isCompleted"] as NSObject == true {
            task["isCompleted"] = false
        } else {
            task["isCompleted"] = true
        }

    task.saveInBackgroundWithBlock { (success, error) -> Void in

        if (error == nil) {
            println("saved checkbox object in background")
        } else {
            println(error!.userInfo)
        }
    }

    self.tableView.reloadData()
}

override func tableView(tableView: UITableView?, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

override func tableView(tableView: UITableView?, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

    if (editingStyle == UITableViewCellEditingStyle.Delete) {

        var task:PFObject = self.taskObjects.objectAtIndex(indexPath.row) as PFObject

        task.deleteInBackgroundWithBlock({ (success, error) -> Void in

            self.fetchAllObjects()

            self.taskObjects.removeObjectAtIndex(indexPath.row)
        })

    } else if editingStyle == .Insert {

    }
}

When working with tables and collection views, all the objects you have in a custom cell can be easily accessed in cellForRowAtIndexPath (for UITables) 使用表和集合视图时,可以轻松地在cellForRowAtIndexPath(用于UITables)中访问自定义单元格中具有的所有对象。

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

    var action = actions[indexPath.row] as Action

    cell.nameLabel?.text = action.name
    cell.listLabel?.text = action.list
    cell.dateLabel?.text = action.date
    cell.checkboxButton = action.isChecked
    cell.checkBoxButton.setImage(UIImage(named:"checkedImage"), forState:UIControlState.Normal)
    return cell
}

more over I would suggest to change constants to variables. 此外,我建议将常量更改为变量。 I'm new to Swift too and "let" declares a static variable. 我也是Swift的新手,“ let”声明了一个静态变量。

I find very cool the use of the conditional operator (?:) in these cases: 在这些情况下,我发现使用条件运算符(?:)非常酷:

cell.checkBoxButton.setImage(UIImage(named:(any_boolean_condition ? "checkedImage" : "uncheckedImage")), forState:UIControlState.Normal)

so it can return one image name for the condition True and another name for the condition False. 因此它可以为条件True返回一个图像名称,为条件False返回另一个图像名称。

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

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