如何在 iPhone 中使用 UISwitch on/off add/remove 数组中的对象
How to add/remove objects in array using UISwitch on/off in iPhone
我在 UITableViewCell 中添加了 UISwitch,但是 如何在 switch get ON/OFF.
时从数组中添加或删除对象
这是我在 cellForRowAtIndexPath 中的代码:
if (indexPath.section == 0)
{
cell.textLabel.text = [menuArray1 objectAtIndex:indexPath.row];
UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero];
if ([userSession.searchedArray count] > 0)
{
if ([userSession.searchedArray containsObject:cell.textLabel.text])
{
switchview.on = YES;
}
}
switchview.tag = indexPath.row;
[switchview addTarget:self action:@selector(switchToggle:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = switchview;
}
//Switch action
-(void)switchToggle:(id)sender
{
UISwitch *theSwitch = (UISwitch *)sender;
NSLog(@"tag %d",theSwitch.tag);
NSInteger i = [sender tag];
if (theSwitch.isOn)
{
NSString *str = [menuArray1 objectAtIndex:i];
[array addObject:str];
userSession.searchedArray = array;
NSLog(@"SearchArray %@",userSession.searchedArray);
}
else
{
[array removeObjectAtIndex:i];
userSession.searchedArray = array;
}
}
当我尝试在 UISwitch 关闭时从数组中删除对象时,我的 应用程序崩溃了 。
我哪里错了?如果 UISwitch 是 on/off.
,请建议我从数组中添加或删除对象的正确方法
提前致谢
首先检查对象是否添加。
添加对象后记录数组。
[array removeObject: [menuArray1 objectAtIndex:i]];
试试这个。
我在 UITableViewCell 中添加了 UISwitch,但是 如何在 switch get ON/OFF.
时从数组中添加或删除对象这是我在 cellForRowAtIndexPath 中的代码:
if (indexPath.section == 0)
{
cell.textLabel.text = [menuArray1 objectAtIndex:indexPath.row];
UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero];
if ([userSession.searchedArray count] > 0)
{
if ([userSession.searchedArray containsObject:cell.textLabel.text])
{
switchview.on = YES;
}
}
switchview.tag = indexPath.row;
[switchview addTarget:self action:@selector(switchToggle:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = switchview;
}
//Switch action
-(void)switchToggle:(id)sender
{
UISwitch *theSwitch = (UISwitch *)sender;
NSLog(@"tag %d",theSwitch.tag);
NSInteger i = [sender tag];
if (theSwitch.isOn)
{
NSString *str = [menuArray1 objectAtIndex:i];
[array addObject:str];
userSession.searchedArray = array;
NSLog(@"SearchArray %@",userSession.searchedArray);
}
else
{
[array removeObjectAtIndex:i];
userSession.searchedArray = array;
}
}
当我尝试在 UISwitch 关闭时从数组中删除对象时,我的 应用程序崩溃了 。
我哪里错了?如果 UISwitch 是 on/off.
,请建议我从数组中添加或删除对象的正确方法提前致谢
首先检查对象是否添加。
添加对象后记录数组。
[array removeObject: [menuArray1 objectAtIndex:i]];
试试这个。