모든 게시물을 읽었으며 모든 솔루션을 여러 번 시도했지만 올바른 기능을 얻을 수 없습니다.선택한 셀을 배열로 저장, 유지 및 검색
로컬 JSON 파일의 데이터로 tableview가 있습니다. 나는 할 수 있도록 사용자가 필요
- 는
- 는
- 선택하지 않은 선택을 삭제 배열에 그 선택을 쓰기 선택된 셀에 여러 셀을
- 쇼 확인 표시를 선택
5. 사용자가보기/나가기를 선택하고 tableview로 돌아 왔을 때 체크 표시가있는 선택 항목을 저장/유지하고, 응용 프로그램을 닫고 다시 엽니 다.
나는 1-4 가지 일을 할 수 있었지만, 나는 5 위에 머물렀고, 내 인생을 생각할 수 없었다. 내가 할 수있는 모든 방법으로 NSUserDefaults를 시도했다. 어떤 도움을 주셔서 감사합니다. 아래는 현재 코드입니다.
또한 왜 셀을 두 번 클릭하여 선택을 취소해야합니까?
@interface FilterViewController() <UISearchResultsUpdating>
@property (nonatomic, strong) NSArray *IngredientsArray;
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) NSMutableArray *searchResults;
@property (nonatomic, strong) NSMutableArray *selectedCell;
@property (nonatomic, strong) NSMutableArray *selectedIngredients;
//I added this property to keep track of the selected row
@property (strong,nonatomic) NSIndexPath *selectedPath;
@end
@implementation FilterViewController {
NSArray *_locations;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.selectedIngredients = [NSMutableArray array];
self.selectedCell = [NSMutableArray array];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
self.lastIndexPath = [defaults objectForKey:@"lastIndexPathUsed"];
// Create a new JSONLoader with a local file URL
JSONLoaderIngreds *jsonLoader = [[JSONLoaderIngreds alloc] init];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"locations" withExtension:@"json"];
// There's no transition in our storyboard to our search results tableview or navigation controller
// so we'll have to grab it using the instantiateViewControllerWithIdentifier: method
UINavigationController *searchResultsController = [[self storyboard] instantiateViewControllerWithIdentifier:@"FilterViewSearchResultsNavController"];
// Our instance of UISearchController will use searchResults
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
// The searchcontroller's searchResultsUpdater property will contain our tableView.
self.searchController.searchResultsUpdater = self;
// create the searchBar programatically.
self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x,
self.searchController.searchBar.frame.origin.y,
self.searchController.searchBar.frame.size.width, 44.0);
self.tableView.tableHeaderView = self.searchController.searchBar;
//Sets LocationsViewController as presenter for LocationDetailViewController after searxh results dsiplayed
//and selected.. Required so searchbar doesn't show in detailsview after segue, and instead, default nav
//controller back button displays.
self.definesPresentationContext = true;
// Load the data on a background queue...
// As we are using a local file it's not really necessary, but if we were connecting to an online URL then we'd need it
//NSString *ingreds = [dict objectForKey:@"ingredients"]
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
_locations = [jsonLoader ingredientsFromJSONFile:url];
// Now that we have the data, reload the table data on the main UI thread
[self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
});
}
// Just before showing the LocationViewController, set the selected Location object
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
LocationsViewController *vc = segue.destinationViewController;
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
vc.location = [_locations objectAtIndex:indexPath.row];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewWillAppear:(BOOL)animated
{
//I added this if clause to select the row that was last selected
if (self.selectedPath != nil) {
[self.tableView selectRowAtIndexPath:self.selectedPath animated:NO scrollPosition:UITableViewScrollPositionNone];
}
}
#pragma mark - Table View Controller Methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
self.selectedPath = indexPath;
NSString *Ingredient = [_locations objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if([self isRowSelectedOnTableView:tableView atIndexPath:indexPath]){
[self.selectedCell removeObject:indexPath];
[self.selectedIngredients removeObject:Ingredient];
cell.accessoryType = UITableViewCellAccessoryNone;
} else {
[self.selectedCell addObject:indexPath];
[self.selectedIngredients addObject:Ingredient];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
NSLog(@"***************Selected Ingredients**************** %@", self.selectedIngredients);
NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
[userdefaults setObject:[NSString stringWithFormat:@"%ld",(long)indexPath.section] forKey:@"lastIndexPathUsed"];
[userdefaults synchronize];
}
-(BOOL)isRowSelectedOnTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath
{
return ([self.selectedCell containsObject:indexPath]) ? YES : NO;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *unifiedID = @"FilterCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:unifiedID];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:unifiedID];
}
cell.textLabel.text = [_locations objectAtIndex:indexPath.row];
cell.imageView.image = [UIImage imageNamed:@"ingredientsicon3232.png"];
//if the indexPath was found among the selected ones, set the checkmark on the cell
cell.accessoryType = ([self isRowSelectedOnTableView:tableView atIndexPath:indexPath]) ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_locations count];
}
UPDATE : 아래의 업데이트 된 코드를 사용하여 NSUserDefaults
에 배열에 대한 선택 사항을 저장하기 위해 제안,하지만 난 여전히 저장하는 데 필요한 cellForRowAtIndexPath
코드를 알아낼 수 없습니다 나는이 변경된 코드 관리
/리콜 체크 표시.
checkFor를 호출하기 위해 cellForRowAtIndexPath를 코딩하는 방법은 무엇입니까? 이 코드 배열에
저장 선택 :
의 viewDidLoad 코드 :
_selections = [NSMutableArray arrayWithArray:(NSArray *)[[NSUserDefaults standardUserDefaults] objectForKey:@"selections"]];
if(_selections == nil){
_selections = [[NSMutableArray alloc] init];
}
didSelectRowAtIndexPath 코드 :
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
{
if ([_selections containsObject: cell.textLabel.text] == NO){
[_selections addObject:cell.textLabel.text];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
[_selections removeObject:cell.textLabel.text];
cell.accessoryType = UITableViewCellAccessoryNone;
}
NSLog(@"***************Selected Ingredients**************** %@", _selections);
NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
[userdefaults setObject:_selections forKey:@"selections"];
[userdefaults synchronize];
NSLog(@"-------------NSUserDefaults------------%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation])
}
내가 이해할 수 있다고 생각하지만 코드에서 어떻게 수행되는지 보여줄 수 있습니까? 나는 여러 가지 방법으로 시도해 보았고 일할 수 없었다. 아직도 배우기. 감사. – Jason
나는 지금 여행 중이다. 몇 시간 안에 예를 보여 드릴 수는 있지만, 지금 당장이 세 단계를 시도해보아야합니다. 전혀 어렵지 않습니다. 그냥 줘. – Harsh
지시에 따라 배열을 사용자 기본값으로 저장하도록 선택 저장을 수행했지만 체크 표시를 유지하는 코드를 파악할 수 없습니다. 코드 예제를 제공 할 수 있습니까? – Jason