UISwitch inside custom UITableViewCell not available

江枫思渺然 提交于 2019-11-29 21:58:40

I did this a while ago. You should change your selctor

[self.keychainSwitch addTarget:self action:@selector(keychainOptionSwitched:) forControlEvents:UIControlEventValueChanged];

And then update your method to

-(void) keychainOptionSwitched:(id)sender {
UISwitch *tempSwitch = (UISwitch *)sender;
}

Now tempSwitch is the switch that was changed.

h4xxr

I spent ages fiddling around with custom UITableViewCells with a simple label and switch on it before I discovered I could just add a UISwitch as an accessory view. You're probably aware of this anyway, and want the custom cell for other reasons, but just in case I wanted to mention this!

You do this as follows (in the -tableView:cellForRowAtIndexPath method):

UISwitch *mySwitch = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
cell.accessoryView = mySwitch;

The accessoryView bit also takes care of the sizing and positioning so we can get away with CGRectZero.

You're then able to use the system control event and setOn method as follows (note we cast it as the UISwitch pointer that we know it is):

[(UISwitch *)cell.accessoryView setOn:YES];   // Or NO, obviously!
[(UISwitch *)cell.accessoryView addTarget:self action:@selector(mySelector)
     forControlEvents:UIControlEventValueChanged];

Hope that helps!

I think whats happening here is that you are trying to invoke the operation when the cell is out of view, so whats going on is that the cell is unloaded at that time therefore you are getting a nil for the keychain switch, once it comes into view then its no longer nil since its reloaded. But i see that you are assigning the switch like so

 self.keychainSwitch = [(RootLabeledSwitchTableCell *)cell labeledSwitch];

Its a reference to the switch in the table cell and you are not retaining it, so it makes since that the switch is becoming nil since , when the cell goes out of view is unloaded and keychainSwitch is becoming nil as a result and therefore your class member is becoming nil as well. You might want to retain keychainSwitch and then when reconstructing your table c ell get the switch out of keychainSwitch, or something of the sort. Hope this helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!