I have a tableview controller, with a label and a switch displayed in a row. To add elements like this, I am using the approach below(as is recommended to avoid the data in the row getting mixed up).
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
....
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UISwitch* testSwitch = [[UISwitch alloc] initWithFrame:
CGRectMake(200,
0.5 * (cell.frame.size.height-30 ),
30, 30)];
testSwitch.tag = 2;//If this is a dynamic value, it only works for 14 rows
[cell.contentView addSubview:testSwitch];
[testSwitch release];
}
UISwitch *switch1 = (UISwitch*) [cell viewWithTag:2];
//cannot set a dynamic value here
switch1.on = [<array value> boolValue];
I need the tag to be a dynamic value depending on the data on the current row so that I can add an actio开发者_运维知识库n method when the value changes, and make according model related changes. However, since the tag is set in the first section, if I make that dynamic, only 14 values(which are the number of rows displayed on the screen) are set. What do I do so that I can store a dynamic value on all the rows of this switch for its target action method to retrieve?
Thanks..
--Edit--- Changed code to
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UISwitch* testSwitch = [[UISwitch alloc] initWithFrame:
CGRectMake(200,
0.5 * (cell.frame.size.height-30 ),
30, 30)];
testSwitch.tag = indexPath.row;//If this is a dynamic value, it only works for 14 rows
[cell.contentView addSubview:testSwitch];
[testSwitch release];
}
UISwitch *switch1 = (UISwitch*) [cell viewWithTag:indexPath.row];
switch1.on = someboolValue; //CRASH as switch1 points to UItablviewcell and not UISwitch.
testSwitch.tag=[indexPath row]
assuming you only have one section.
ok, it now sounds like you are having a problem that [cell viewWithTag:indexPath.row]
is locating the cell and not it's subview so assuming you only have one uiswitch subview:
for (UIView *v in [cell subviews]) {
if ([v isKindOfClass:[UISwitch class]]) {
v.on = someboolValue;
}
}
精彩评论