MachTurtle MachTurtle - 1 month ago 6
Swift Question

How do I use UIStepper to change a property in a Realm Model Object?

I currently have a

ViewController
with a
TableView
inside it called
SelectedListItemsViewController
. This
ViewController
's
TableView
is populated by a custom cell class called
SelectedListItemsTableViewCell
.

I have an array of Realm Model Objects called
selectedListItems
, each of which has several properties. The
SelectedListItemsTableViewCell
populates the
TableView
with the
listItem
property of that
indexPath.row
's object, and each row has a
UIStepper
with a
UILabel
next to it that (as of now) shows
UIStepper.value
for each row. Ideally, the label will reflect the
listItemWeight
property of each row, and change it when incrementing or decrementing that row.

This is my custom cell:

class SelectedListItemsTableViewCell: UITableViewCell {

@IBOutlet var selectedListItemLabel: UILabel!
@IBOutlet weak var listItemWeightLabel: UILabel!
@IBOutlet weak var stepperControl: UIStepper!

@IBAction func stepperValueChanged(sender: UIStepper) {

listItemWeightLabel.text = Int(sender.value).description

}
}


And in my
ViewController
's
cellForRowAtIndexPath
, I've configured the cell like so:

// Configure the cell...
cell.selectedListItemLabel.text = selectedListItems[indexPath.row].listItem

cell.listItemWeightLabel.text = "\(selectedListItems[indexPath.row].listItemWeight)"


Which perfectly loads the
listItem
property, and the
listItemWeight
property shows up correctly, but as soon as I increment or decrement on the
UIStepper
it gets messed up.

How do I properly link my UILabel and UIStepper to the
[indexPath.row].listItemWeight
?

Answer

The above answer was helpful in leading me to the actual solution of my issue, but if anyone in the future is curious - I ended up using a closure.

In my custom cell class, I did

@IBAction func stepperValueChanged(sender: UIStepper) {

    selectedListItemLabel.text = Int(sender.value).description
    tapped?(self)

}

And in my view controller, I did

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

    cell.stepperControl.value = selectedListItems[indexPath.row].listItemWeight

    // Configure the cell...

    cell.tapped = { (selectedCell) -> Void in

        selectedListItems[indexPath.row].listItemWeight = cell.stepperControl.value

    }

Which allowed me to access each cell's UIStepper in the view controller file.

It helped to read flashadvanced's Option 2 answer in this thread.

Comments