【问题标题】:How to save the checkmarks in uitableview and show them when the user comes back again to the view?如何在 uitableview 中保存复选标记并在用户再次返回视图时显示它们?
【发布时间】:2017-02-05 01:45:49
【问题描述】:

我正在使用以下代码在 uitableview 中显示复选标记

  {
  //  NSArray *tableContents;
    NSMutableArray *selectedMarks; // You need probably to save the selected cells for use in the future.
}
@property (strong, nonatomic) IBOutlet UITableView *languageTableView;
@property (nonatomic, strong) NSArray *tableContents;

@end

@implementation QPLanguageSettingsController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initialisation];
    selectedMarks = [NSMutableArray new];
}
#pragma mark - View Life Cycle

-(void)initialisation
{
    _tableContents = [NSArray arrayWithObjects:@"English",@"Spanish",@"Russian",@"Arabic",@"Portuguese",@"French",@"German",@"German",@"German",@"German",@"German",@"German",@"German",@"German", nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableView delegate & datasources

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 14;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"newFriendCell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    //etc.

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.backgroundColor = [UIColor clearColor];
    [cell setIndentationLevel:3];
    [cell setIndentationWidth:10];
     NSString *text = [_tableContents objectAtIndex:[indexPath row]];
     //cell.isSelected = [selectedMarks containsObject:text] ? YES : NO;
     cell.textLabel.text = text;
     NSDictionary *item = [_tableContents objectAtIndex:indexPath.row];
    if ([selectedMarks containsObject:item])
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;

    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //if you want only one cell to be selected use a local NSIndexPath property instead of array. and use the code below
    //self.selectedIndexPath = indexPath;

    //the below code will allow multiple selection
     NSDictionary *item = [_tableContents objectAtIndex:indexPath.row];
    if ([selectedMarks containsObject:item])
    {
        [selectedMarks removeObject:item];
    }
    else
    {
        [selectedMarks addObject:item];
    }
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

但问题是,当我再次访问视图控制器时,所有复选标记都消失了。如何解决它。请记住,我在 uitableview 中使用多项选择。

【问题讨论】:

  • 将数据存储在 Core-data 或 Sqlite 或 Plist 或用户默认值中。
  • 如何在 nsuserdefaults 中存储这个请贴出代码
  • 在数组中保存复选标记,然后使用 userdefaults [[NSUserDefaults standardUserDefaults] setObject:yourdataAry forKey:@"checkMarks"]; 或使用本地数据库保存数组。
  • @Ashley Rodrigues 请检查我的代码。我将添加一个示例项目进行测试
  • @Ashley Rodrigues 我在我的 GitHub 中添加了一个示例项目。请检查并回复

标签: ios objective-c uitableview


【解决方案1】:

使用以下代码:

#import "ViewController.h"

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *languagesTableView;

@property (strong, nonatomic) NSArray *languagesArray;

@property (strong, nonatomic) NSMutableArray *checkMarksArray;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self.languagesTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    self.languagesArray = [NSArray arrayWithObjects:@"English",@"Spanish",@"Russian",@"Arabic",@"Portuguese",@"French",@"German", nil];
    self.checkMarksArray = [[NSMutableArray alloc]init];
    if( [[NSUserDefaults standardUserDefaults]objectForKey:@"selectedRowsArray"])
    {
       self.checkMarksArray = [[[NSUserDefaults standardUserDefaults]objectForKey:@"selectedRowsArray"] mutableCopy];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.languagesArray.count;

}

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

    UITableViewCell *languagesCell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    languagesCell.textLabel.text = self.languagesArray[indexPath.row];
    if([self.checkMarksArray containsObject:[NSNumber numberWithLong:indexPath.row]])
    {
        languagesCell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else
    {
        languagesCell.accessoryType = UITableViewCellAccessoryNone;
    }

    [[NSUserDefaults standardUserDefaults]setObject:self.checkMarksArray forKey:@"selectedRowsArray"];
    [[NSUserDefaults standardUserDefaults]synchronize];

    return languagesCell;


}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if([self.checkMarksArray containsObject:[NSNumber numberWithLong:indexPath.row]])
    {
        [self.checkMarksArray removeObject:[NSNumber numberWithLong:indexPath.row]];
    }
    else
    {
        [self.checkMarksArray addObject:[NSNumber numberWithLong:indexPath.row]];
    }

    [self.languagesTableView reloadData];
}

@end

查看此 GitHub 链接:

https://github.com/k-sathireddy/TableViewSelectedCheckMarks

【讨论】:

  • 我已经检查过了...有什么办法可以让选定的行值附加逗号??
  • 您想将数组转换为逗号分隔的字符串吗?
【解决方案2】:

您可以创建一个 Singleton 并在其上存储数据:

Singleton.h

@interface Singleton : NSObject

@property (nonatomic, strong) NSArray *rowsChecked;

+ (Singleton *)sharedInstance;
+ (NSArray  *)getRowsChecked;
+ (void)setRowsChecked:(NSArray *)rowsChecked;

@end

Singleton.m

    #import "Singleton.h"

@implementation Singleton

        static Singleton *sharedObject;

        + (Singleton *)sharedInstance;
        {
            if (sharedObject == nil) {
                static dispatch_once_t pred;
                dispatch_once(&pred, ^{
                    sharedObject = [[Singleton alloc] init];
                });
            }
            return sharedObject;
        }

        + (NSArray *)getRowsChecked
        {
            Singleton *singleton = [Singleton sharedInstance];
            return singleton.rowsChecked;
        }

        + (void)setRowsChecked:(NSArray *)rowsChecked
        {
            Singleton *singleton = [Singleton sharedInstance];
            singleton.rowsChecked= rowsChecked;
        }

    @end

并访问您的单例:

[[Singleton sharedInstance] getRowsChecked]

// or

[[Singleton sharedInstance] setRowsChecked:anArray];

【讨论】:

  • 酷,那么他是如何按照你的 ans 插入和获取选中的数组的呢?
  • 访问 getRowsChecked 并插入 setRowsChecked
  • 那么一次可以保存多少个实例..如果需要保存多个复选标记数组怎么办?
【解决方案3】:

我尝试为您的问题找到解决方案。我成功解决了。它运行良好。

这是示例之一。试试这个代码。它工作正常。

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) IBOutlet UITableView *tableViewCheckMarkPreviousSelectionUpdate;
@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()
{
   NSMutableArray *arrProductSelection,*arrProductSelectDeSelectCheckMark;
   NSArray *arrayFetchFromDefaults;
}

@end

@implementation ViewController

@synthesize tableViewCheckMarkPreviousSelectionUpdate;

- (void)viewDidLoad
{
   [super viewDidLoad];
   arrProductSelection = [[NSMutableArray alloc]initWithObjects:@"iPhone",@"iPad",@"iPod",@"iTV",@"iWatch",@"iMac",nil];
}
- (void)didReceiveMemoryWarning
{
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated
{
  NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  arrayFetchFromDefaults = [userDefaults objectForKey:@"selectedcheckmark"];
  arrProductSelectDeSelectCheckMark = [[NSMutableArray alloc]initWithArray:arrayFetchFromDefaults];
  if(arrProductSelectDeSelectCheckMark.count == 0)
  {
     arrProductSelectDeSelectCheckMark = [[NSMutableArray alloc]init];
     for(int j=0;j<[arrProductSelection count];j++)
     {
        [arrProductSelectDeSelectCheckMark addObject:@"deselected"];
     }
   }
   [tableViewCheckMarkPreviousSelectionUpdate reloadData];
}

#pragma mark - UITableViewDataSource Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
   return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return arrProductSelection.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   NSString *strCell = @"cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
   if(cell==nil)
   {
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCell];
   }
   if([[arrProductSelectDeSelectCheckMark objectAtIndex:indexPath.row] isEqualToString:@"deselected"])
     cell.accessoryType = UITableViewCellAccessoryNone;
   else
     cell.accessoryType = UITableViewCellAccessoryCheckmark;
   cell.textLabel.text = [arrProductSelection objectAtIndex:indexPath.row];
   return cell;
}

#pragma mark - UITableViewDelegate Methods
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    @try
    {
        CGPoint touchPoint = [cell convertPoint:CGPointZero toView:tableViewCheckMarkSelectionUpdate];
        NSIndexPath *indexPath = [tableViewCheckMarkSelectionUpdate indexPathForRowAtPoint:touchPoint];
        NSLog(@"%@",arrProductSelectDeSelectCheckMark);
        if([arrProductSelectDeSelectCheckMark count]==0)
        {
           for(int i=0; i<[arrProductSelection count]; i++)
           {
             [arrProductSelectDeSelectCheckMark addObject:@"deselected"];
           }
        }
        if([[arrProductSelectDeSelectCheckMark objectAtIndex:indexPath.row] isEqualToString:@"deselected"])
        {
           cell.accessoryType = UITableViewCellAccessoryCheckmark;
           [arrProductSelectDeSelectCheckMark replaceObjectAtIndex:indexPath.row withObject:@"selected"];
        }
        else
        {
           cell.accessoryType = UITableViewCellAccessoryNone;
           [arrProductSelectDeSelectCheckMark replaceObjectAtIndex:indexPath.row withObject:@"deselected"];
        }

        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:arrProductSelectDeSelectCheckMark forKey:@"selectedcheckmark"];
        [defaults synchronize];
      }
   @catch (NSException *exception) {
    NSLog(@"The exception is-%@",exception);
   }
}
@end

【讨论】:

  • 在 arrProductSelectDeSelectCheckMark 数组中,我们得到选择和取消选择的项目。
【解决方案4】:

您有多种解决方案:

  1. 在设备上使用合理的 DB,例如 Core-dataSQLite,这实际上适合您的用例,但数字 3 更适合您的用例。
  2. 使用NSUserDefaults:

在运行时,您使用NSUserDefaults 对象从用户的默认数据库中读取您的应用程序使用的默认值。 NSUserDefaults 缓存信息以避免每次需要默认值时都必须打开用户的默认值数据库

您可以找到一个示例here。但是NSUserDefaults 是为了保存设置/配置/设置信息或者可能是用户信息,而不是用于您需要的用例。

  1. 使用NSCoder,我认为这适合您的用例。

【讨论】:

  • 请告诉我如何使用nsuserdefaults
  • 你看答案了吗?此外,您应该避免在 NSUserDefaults 中保存您需要的内容。你需要的是 NSCoder。
猜你喜欢
  • 2019-11-27
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多