Reputation: 99
Is there a way to know the number of UISwitch that is "ON" state in a UITableView? I have a multiple UITableViewCell in a UITableView - each has an UISwitch that is "ON" state. I think the code would be more something like:
for ([mySwitch on] in tableView){
code goes here.....
}
Upvotes: 0
Views: 246
Reputation: 506
you know, ios developing is using the MVC pattern, the content you display in a view or the states of UI widgets should binding with your view models, as in your case, you can create a view model like SwichViewModel
which has a BOOL property isSwitchOn
, when you load your table view, you turn on/off the switch base on its view model's isSwitchOn
property, and the count of turned on switches is the count of the view models which isSwitchOn
is YES. Below is my example code:
//create the view model
@interface SwitchViewModel : NSObject
@property (assign, nonatomic) BOOL isSwitchOn;
@end
@interface TableViewController ()
@property (strong, nonatomic) NSArray *switchViewModels;
@end
@implementation TableViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.switchViewModels = [self getData]; // you need to implement the getData method
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.switchViewModels.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
SwitchViewModel *model = self.switchViewModels[indexPath.row];
SwitchTVCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID" forIndexPath:indexPath];
cell.switcher.on = model.isSwitchOn;
return cell;
}
- (NSInteger)getCountOfSwitchsOn{
NSArray *switchsOn = [self.switchViewModels filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"isSwitchOn == %@", @(YES)]];
return switchsOn.count;
}
@end
Upvotes: 0
Reputation: 9898
You have to maintain mutable array ( NSMutableArray ) in accordance of UISwitch, when switch goes on / off you have to maintain that value ( flag ) in mutable array.
When you reload UITableView make all array items with ON flag. when you change your switch to off, then fire a method of switch and as per indexpath.row you have to OFF flag at objectAtIndex in array.
So that array will provide you all values of no of switches are on or off.
Upvotes: 2