开发者

Problem getting which switch was changed (UISwitch as accessory type)

I need help figuring out which Accessory Type Switch has been changed.

I have a list of games in a UITableView. I've added a UISwitch as an accessory type, and each switch reacts to touch, changing its state and notifying its action receiver.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{


UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cell"];
if(nil == cell){
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"cell"]autorelease];

}


Games *games=[appDelegate.hidden objectAtIndex:indexPath.row];
cell.textLabel.text = games.gameName;

//the switch is defined here, as is its target-action

testSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0.0, 0.0, 74.0, 27.0)];
[testSwitch addTarget:self action:@selector(button_Clicked:)
     forControlEvents:UIControlEventValueChanged];

//If I used the tags
    testSwitch.tag=indexPath.row;

[testSwitch setOn:YES];
cell.accessoryView=testSwit开发者_JAVA百科ch;


[games release];

return cell;
}

And the target-action: see comments

- (void)button_Clicked:(id)sender{
    UISwitch* switchControl = sender; //if I make this an int, the switches 
                //have different numbers.  If it's cast as a string, it's gobbledegook.

//This always returns 0.  I can't tell it it's not getting anything (ie it's 
                // nil), or if the row always comes up 0.

    UITableViewCell *cell = (UITableViewCell *)[sender superview];
    NSIndexPath *x=[table indexPathForCell:cell];
    NSLog(@"%i",x.row);


}

I see two potential problems. One, I need to make a switch for every row, uniquely named. Two, I'm not getting the cell correctly.

If anyone can see my mistake(s), any help is welcome.

I've looked through everything I can find on stackoverflow, and several pages into 5 or 6 different search queries on Google, the two above examples in the target-action method are the best I've found.


Try this

set a tag like testSwitch.tag = indexpath.row in your cellForRowAtIndexPath

then in your button clicked event

UISwitch *tswitch = (UISwitch *)sender;

int row = tswitch.tag;

NSlog(@"Your selected array value :%@",[your array objectatindex:row]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜