簡體   English   中英

如何使用iPhone中的UISwitch打開/關閉來添加/刪除數組中的對象

[英]How to add/remove objects in array using UISwitch on/off in iPhone

我在UITableViewCell中添加了UISwitch,但是當開關打開/關閉時如何從數組中添加或刪除對象。

這是我在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,請向我建議添加或刪除數組對象的正確方法。

提前致謝

hii首先檢查是否添加了對象。

添加對象后記錄數組。

 [array removeObject: [menuArray1 objectAtIndex:i]];

嘗試這個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM