簡體   English   中英

Swift:在點擊時在表格視圖中更改按鈕圖像

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

我使用Swift創建了一個iPhone的Xcode項目,后端使用了Parse。 我當前的問題是將待辦事項列表應用程序創建為較大應用程序的一個選項卡。

在自定義原型單元內,我想有一個復選框按鈕,該按鈕可以在單擊時更改其圖像,以及更改該單元的isChecked:Bool變量。 我已經完成了大部分工作,但是在設置和訪問此按鈕的適當變量方面遇到了麻煩。

編輯:由於下面的答案和其他資源,我終於為此復選框功能編寫了工作代碼。 本質上,按鈕的tag屬性設置為等於PFObject的indexPath.row。 由於我最初的問題有點寬泛,因此我在下面更新我的代碼,以便它可以幫助從事類似功能的其他新開發人員。 也許有更好的方法,但這似乎可行。

// 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 {

    }
}

使用表和集合視圖時,可以輕松地在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
}

此外,我建議將常量更改為變量。 我也是Swift的新手,“ let”聲明了一個靜態變量。

在這些情況下,我發現使用條件運算符(?:)非常酷:

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

因此它可以為條件True返回一個圖像名稱,為條件False返回另一個圖像名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM