#ios #objective-c #uitableview
#iOS #objective-c #uitableview
Вопрос:
Я использую флажки в UITableView для выбора языка и передачи этих языков на серверную часть при обновлении профиля. Теперь, когда я снова вхожу в систему с пользователем, я также получаю языки, которые я обновил из выбора. Итак, я хочу показать тики в UITableView на основе языка, исходящего из серверной части. Как это возможно?
- (void)viewDidLoad
{
[super viewDidLoad];
arrProductSelection = [[NSMutableArray alloc]initWithObjects:@"Afar",@"Abkhazian",@"Afrikaans",@"Amharic",@"Arabic",@"Assamese",@"Aymara",@"Azerbaijani",@"Bashkir",@"Belarusian",@"Bulgarian",@"Bihari",@"Bislama",@"Bengali",@"Bislama",@"Tibetan",@"Breton",@"Bosnian",@"Catalan",@"Cebuano",@"Cherokee",@"Corsican",@"Seselwa",@"Czech",@"Welsh",@"Danish",@"German",@"Dhivehi",@"Dzongkha",@"Greek",@"English",@"Esperanto",@"Spanish",@"Estonian",@"Basque",@"Persian",@"Finnish",@"Fijian",@"Faroese",@"French",@"Frisian",@"Irish",@"Scots Gaelic",@"Galician",@"Guarani",@"Gujarati",@"Manx",@"Hausa",@"Hawaiian",@"Bislama",@"Hindi",@"Hmong",@"Croatian",@"Haitian Creole",@"Hungarian",@"Armenian",@"Interlingua",@"Indonesian",@"Igbo",@"Inupiak",@"Icelandic",@"Italian",@"Inuktitut",@"Hebrew",@"Japanese",@"Javanese",@"Georgian",@"Khasi",@"Kazakh",@"Greenlandic",@"Khmer",@"Kannada",@"Korean",@"Kashmiri",@"Kurdish",@"Kyrgyz",@"Latin",@"Luxembourgish",@"Ganda",@"Limbu",@"Lingala",@"Laothian",@"Lithuanian",@"Latvian",@"Malagasy",@"Mauritian Creole",@"Malagasy",@"Maori",@"Macedonian",@"Malayalam",@"Mongolian",@"Marathi",@"Malay",@"Maltese",@"Burmese",@"Nauru",@"Nepali",@"Dutch",@"Norwegian",@"Ndebele",@"Pedi",@"Nyanja",@"Occitan",@"Oromo",@"Oriya",@"Punjabi",@"Polish",@"Pashto",@"Portuguese",@"Quechua",@"Rhaeto Romance",@"Scots",@"Sindhi",@"Sango",@"Sinhalese",@"Slovak",@"Slovenian",@"Samoan",@"Shona",@"Somali",@"Albanian",@"Serbian",@"Siswant",@"Sesotho",@"Sundanese",@"Swedish",@"Swahili",@"Syriac",@"Tamil",@"Telugu",@"Tajik",@"Thai",@"Tigrinya",@"Turkmen",@"Tagalog",@"Sundanese",@"Tswana",@"Tonga",@"Turkish",@"Tsonga",@"Tatar",@"Uighur",@"Ukrainian",@"Urdu",@"Uzbek",@"Venda",@"Vietnamese",@"Volapuk",@"Waray Philippines",@"Wolof",@"Xhosa",@"WYiddish",@"Yoruba",@"WZhuang",@"Chinese",@"Hant,Chinese",@"Zulu",nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated
{
[languageTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:0];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
arrayFetchFromDefaults = [userDefaults objectForKey:@"selectedcheckmark"];
arrProductSelectDeSelectCheckMark = [[NSMutableArray alloc]initWithArray:arrayFetchFromDefaults];
NSLog(@"Array from defaults %@",arrayFetchFromDefaults);
if(arrProductSelectDeSelectCheckMark.count == 0)
{
arrProductSelectDeSelectCheckMark = [[NSMutableArray alloc]init];
for(int j=0;j<[arrProductSelection count];j )
{
[arrProductSelectDeSelectCheckMark addObject:@"deselected"];
}
}
NSMutableArray *arrSelected = [[NSMutableArray alloc] init];
for (int i= 0;i< arrayFetchFromDefaults.count ;i )
{
if([[arrayFetchFromDefaults objectAtIndex:i] isEqualToString:@"selected"])
{
NSLog(@"array array %@",[arrProductSelection objectAtIndex:i]);
[arrSelected addObject:arrProductSelection[i]];
}
}
self.strSelected = [arrSelected componentsJoinedByString:@","];
NSLog(@"%@", _strSelected);
//[self gatherFBIds];
[languageTableView 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];
cell.textLabel.textColor = [UIColor whiteColor];
cell.backgroundColor = [UIColor clearColor];
cell.tintColor = [UIColor greenColor];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSMutableArray *arrSelected = [[NSMutableArray alloc] init];
for (int i= 0;i< arrayFetchFromDefaults.count ;i )
{
if([[arrayFetchFromDefaults objectAtIndex:i] isEqualToString:@"selected"])
{
NSLog(@"array array %@",[arrProductSelection objectAtIndex:i]);
[arrSelected addObject:arrProductSelection[i]];
}
}
self.strSelected = [arrSelected componentsJoinedByString:@","];
NSLog(@"%@", _strSelected);
// [self gatherFBIds];
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:languageTableView];
NSIndexPath *indexPath = [languageTableView indexPathForRowAtPoint:touchPoint];
NSLog(@" Check mark %@",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"];
NSLog(@" Check mark 1 %@",arrProductSelectDeSelectCheckMark);
NSMutableArray *arrSelected = [[NSMutableArray alloc] init];
for (int i= 0;i< arrProductSelectDeSelectCheckMark.count ;i )
{
if([[arrProductSelectDeSelectCheckMark objectAtIndex:i] isEqualToString:@"selected"])
{
NSLog(@"array array %@",[arrProductSelection objectAtIndex:i]);
[arrSelected addObject:arrProductSelection[i]];
}
}
self.strSelected = [arrSelected componentsJoinedByString:@","];
NSLog(@"%@", _strSelected);
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
[arrProductSelectDeSelectCheckMark replaceObjectAtIndex:indexPath.row withObject:@"deselected"];
NSLog(@" Check mark 2 %@",arrProductSelectDeSelectCheckMark);
NSMutableArray *arrSelected = [[NSMutableArray alloc] init];
for (int i= 0;i< arrProductSelectDeSelectCheckMark.count ;i )
{
if([[arrProductSelectDeSelectCheckMark objectAtIndex:i] isEqualToString:@"selected"])
{
NSLog(@"array array %@",[arrProductSelection objectAtIndex:i]);
[arrSelected addObject:arrProductSelection[i]];
}
}
self.strSelected = [arrSelected componentsJoinedByString:@","];
NSLog(@"%@", _strSelected);
}
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:arrProductSelectDeSelectCheckMark forKey:@"selectedcheckmark"];
[defaults synchronize];
}
@catch (NSException *exception) {
NSLog(@"The exception is-%@",exception);
}
}
Комментарии:
1. вам нужно сравнить выбранный язык со списком языков и отметить его.
2. При создании ячейки в методе cellForRowAtIndexPath вы можете проверить, находится ли объект в массиве SelectedItems, и обновить его. Нет необходимости запускать отдельный цикл for
3. как это возможно??
4. @AshleyRodrigues проверьте мои ответы, если они подходят..
Ответ №1:
Вы можете добавить логику в метод источника данных tableview.
-(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];
}
for(NSString *string in arrProductSelectDeSelectCheckMark)
{
if([string isEqualToString:@"SomeString"])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
//rest of code
return cell;
}
Измените его в соответствии с вашими потребностями.