Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling multiple UISwitch controls in a table view without using tag property

I have a table view controller with multiple UISwitch controls in them. I set the delegate to the table view controller with the same action for all switches. I need to be able to determine what switch was changed, so I create an array of strings that contains the name of each switch. The indexes in the array will be put in the tag property of each UISwitch.

However, I'm ready using the tag property for something else, namely to find the right control in the cell in cellForRowAtIndexPath with viewWithTag! (There are several things I need to set within each cell.)

So, am I thinking along the right lines here? I feel I'm rather limited in how I find out exactly which UISwitch changed its value, so I can do something useful with it.

like image 597
Thaurin Avatar asked Apr 01 '10 10:04

Thaurin


2 Answers

I fixed this by subclassing UISwitch like so:

@interface NamedUISwitch : UISwitch {
NSString *name;

}

It seems elegant (no index arrays required) and the tag property is free to do whatever it wants.

I read that you have to be careful with subclassing in Objective-C, though...

like image 146
Thaurin Avatar answered Oct 23 '22 05:10

Thaurin


I have written a UISwitch subclass with a block based hander for value change control events which can help when trying to track which switch's value has changed. Ideally, we could do something similar with composition rather than subclassing, but this works well for my needs.

https://gist.github.com/3958325

You can use it like this:

ZUISwitch *mySwitch = [ZUISwitch alloc] init];

[mySwitch onValueChange:^(UISwitch *uiSwitch) {
        if (uiSwitch.on) {
            // do something
        } else {
            // do something else
        }
    }];

You can also use it from a XIB file, by dragging a switch onto your view, and then changing its class to ZUISwitch

like image 36
Willster Avatar answered Oct 23 '22 05:10

Willster