mvasco
mvasco

Reputation: 5101

Getting value of object attribute when touching button inside table view cell

I have a tableview with custom cells. On each cell there are two buttons.

I am using core data to populate the tableview. Each fetched object has a value for the attribute "prioridad" One of the buttons should update the value of the attribute.

What I need is to know hot to get the current value of "prioridad" of the selected row object when the button is touched.

I have included the following code in the cellForRowAtIndexPath method:

...
// subir prioridad
        let image13 = UIImage(named: "subir") as UIImage?
        let button13   = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
        button13.frame = CGRectMake(260, 35, 15, 15)
        button13.setImage(image13, forState: .Normal)
        cell.addSubview(button13)

        button13.tag = indexPath.row;

        button13.addTarget(self, action: Selector("selectItem:"), forControlEvents: UIControlEvents.TouchUpInside)
...

and then I have created the function :

//receptor de subir prioridad
func selectItem(sender:UIButton){

    println("Selected item in row \(sender.tag)")


}

I need to update the value of the attribute "prioridad" of the selected object. And then update it depending on its current value, and then save the object and reload the table view.

Than you

Upvotes: 1

Views: 79

Answers (2)

mvasco
mvasco

Reputation: 5101

After a long search, I have found a way to solve my issue.

I want to share it with you:

func selectItem(sender:UIButton){

    println("Selected item in row \(sender.tag)")

    //update the tableView
    let indexPath = NSIndexPath(forRow: sender.tag, inSection: 0)
    let fetchedObject: AnyObject = self.fetchedResultsController.objectAtIndexPath(indexPath)

    var prioridad = fetchedObject.valueForKey("prioridad") as! String
    println (prioridad)
 ...and here I will update prioridad and reload the tableview...   
}

Upvotes: 0

bdrell
bdrell

Reputation: 194

I would do this a little differently.

On your UITableViewCell subclass, you can add a block property to the cell that gets run whenever the button is tapped. Then, in cellForRowAtIndexPath you can create the block and have the block update the Core Data object.

On your cell subclass, you would have:

@property (nonatomic, copy) void(^buttonTappedBlock)();

Then, in cellForRowAtIndexPath you would do:

cell.buttonTappedBlock = ^{
    object.prioridad++;
    [tableView reloadData];
};

or something similar.

Upvotes: 1

Related Questions