Я использую пользовательские кнопки флажка в моем представлении таблицы и хочу сохранить данные выбранной ячейки на изменяемый массив .... кто может мне помочь ... СпасибоКак сохранить данные Tableview ячейки
ответ
создать изменяемый массив для хранения выбранных данных, позволяет называть его «yourSeparatedData», установите метку вашего флажок в cellForRowAtIndexPath и установить onCheck: метод в качестве мишени. код будет выглядеть следующим образом:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = @"setMe";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyle………
}
checkBox = [UIButton buttonWithType:UIButtonTypeRoundedRect];
checkBox.frame = CGRectMake(customizeMe);
if(yourSeparatedData && [yourSeparatedData indexOfObject:[yourTableViewDataSource objectAtIndex:indexPath.row]] != NSNotFound)
{
[checkBox setBackgroundImage:[UIImage imageNamed:@"check.png"] forState:UIControlStateNormal];
}
else {
[checkBox setBackgroundImage:[UIImage imageNamed:@"unCheck.png"] forState:UIControlStateNormal];
}
[checkBox addTarget:self action:@selector(onCheck:) forControlEvents:UIControlEventTouchUpInside];
[checkBox setTag:indexPath.row];
[cell addSubview:checkBox];
return cell;
}
-(void)onCheck:(id)sender {
if(yourSeparatedData && [yourSeparatedData indexOfObject:[yourTableViewDataSource objectAtIndex:[sender tag]]] != NSNotFound)
{
[sender setBackgroundImage:[UIImage imageNamed:@"unCheck.png"] forState:UIControlStateNormal];
[yourSeparatedData removeObject:[yourTableViewDataSource objectAtIndex:[sender tag]]];
}
else {
[sender setBackgroundImage:[UIImage imageNamed:@"check.png"] forState:UIControlStateNormal];
[yourSeparatedData addObject:[yourTableViewDataSource objectAtIndex:[sender tag]]];
}
[yourTableView reloadData];
}
этот код не проверяется, вы используете опцию таким образом я предполагал, что вы хотите отделить не только один данные, в конце выбор, у вас будет «yourSeparatedData» с объектами, выбранными из вашего tableView.
приветствия .... ваш код мне очень помог. –
добро пожаловать :) – janusbalatbat
У вас есть для этого вручную, в UITableView или UITableViewController нет возможности сделать это автоматически.
Когда пользователь выбирает любую ячейку, а затем в файле didSelectRowAtIndexPath вы можете добавить выбранный объект динамически.
[someMutableArr addObject:[tableArr objectAtIndex:indexPath.row]];
Я использую пользовательские кнопки ... поэтому я не могу добавить их в массив, нажав на строку ... что мне делать ??? –
Попробуйте
- (void)onButtonClick {
int numberOfSections = [tableView numberOfSections];
for (int section = 0; section < numberOfSections; section++) {
int numberOfRows = [tableView numberOfRowsInSection:section];
for (int row = 0; row < numberOfRows; row++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
// Cell is selected
//here you can add that values into an array
} else {
// Cell is not selected
}
}
}
}
как я могу сохранить выбранные строки в массиве ??? –
вы можете попробовать настраиваемое действие в UITableView камере кнопки prees, вы можете также использовать поставить флажок изображения и нажмите кнопку вы можете изменить изображение в зарегистрированном здесь код
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"identifire"];
cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"identifire"] autorelease];
cell.detailTextLabel.text=[id_Array objectAtIndex:indexPath.row];
cell.detailTextLabel.hidden=YES;
button = [UIButton buttonWithType:UIButtonTypeCustom];
NSString *path1 = [[NSBundle mainBundle] pathForResource:@"n_cross" ofType:@"png"];
UIImage *buttonImage1 = [[UIImage alloc] initWithContentsOfFile:path1];
[button setImage:buttonImage1 forState:UIControlStateNormal];
[button addTarget:self
action:@selector(customActionPressed:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Custom Action" forState:UIControlStateNormal];
button.frame = CGRectMake(245.0f, 20.0f, 40.0f, 40.0f);
[cell addSubview:button];
[buttonImage1 release];
CGRect imageFrame=CGRectMake(10,8,50,50);
self.cellimage=[[[UIImageView alloc] initWithFrame:imageFrame] autorelease];
self.cellimage.image=[imageIdArray objectAtIndex:indexPath.row];
[cell.contentView addSubview:self.cellimage];
return cell;
}
-(void)customActionPressed :(id)sender
{
//Get the superview from this button which will be our cell
UITableViewCell *owningCell = (UITableViewCell*)[sender superview];
NSIndexPath *cell = [_tableView indexPathForCell:owningCell];
NSString *uid=[id_Array objectAtIndex:cell.row];
[id_Array removeObjectAtIndex:cell.row];
[_tableView reloadData];
[self performSelectorInBackground:@selector(ignoreRequest:) withObject:uid];
}
здесь я иметь id_Array и при выборе ячейки я просто удалить объект по этому индексу
- 1. Сохранить данные TableView
- 2. JavaFX TableView как получить данные ячейки?
- 3. Как обновить ячейки tableView?
- 4. Получить данные ячейки TableView с помощью MouseEvent
- 5. Постоянно обновлять данные внутри ячейки в TableView
- 6. TableView отображает ячейки как раздел
- 7. Как исправить высоту ячейки tableview
- 8. Как сохранить данные фрейма
- 9. Ячейки в tableview
- 10. Отключить ячейки TableView
- 11. TableView и пользовательские ячейки
- 12. Сохранение цвета фона ячейки tableview
- 13. Размер изображения ячейки TableView
- 14. TableView с редактированием ячейки
- 15. TableView добавление ячейки
- 16. Перезагрузка Активные ячейки tableview
- 17. Удаление ячейки tableView SWIFT
- 18. Отмените изменение ячейки TableView
- 19. Ячейки Tableview от Firebase
- 20. Tableview внутри ячейки просмотра коллекции
- 21. Динамический TableView внутри ячейки Static tableview
- 22. TableView перемешивает ячейки
- 23. tableView ячейки освежающие авто?
- 24. Ячейки Tableview всегда пусты
- 25. Swift - Выбор ячейки TableView
- 26. TableView показывает пустые ячейки
- 27. TableView не загружает ячейки
- 28. Удаление ячейки TableView, заполненной словарем
- 29. iOS - Как повторно инициализировать ячейки tableview
- 30. Как изменить выбранные данные ячейки постоянно?
у вас уже есть данные, вам просто нужно, чтобы получить конкретные данные и хранить его другой mutablearray, я прав? – janusbalatbat
отправил мой ответ ... :) – janusbalatbat