Как сделать эксклюзивный список UITableView для галочек? - PullRequest
0 голосов
/ 08 апреля 2011

Я пытаюсь создать UITableView, который, когда пользователь выбирает ячейку, отображает флажок, а если пользователь выбирает другую ячейку, он удаляет отметку предыдущей выбранной ячейки и ставит отметку на новой выбранной ячейке. Я искал по всему Интернету, но нет хороших примеров, которые действительно работают. У Apple есть некоторый пример кода, расположенный здесь , который объясняет и делает именно то, что я хочу сделать, но когда я копирую и вставляю его в свой проект, я получаю ошибки. Я пытался исправить ошибки, но Apple пропустила некоторые объявления или что-то в этом роде. Единственная ошибка, которую я получаю сейчас, которую я не могу исправить, это self.currentCategory - это не объект и не найден. Итак, мой вопрос: как я могу исправить код Apple, чтобы он работал? Может ли кто-нибудь объявить / объяснить все недостающие части для меня? Вот код Apple:

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

    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSInteger catIndex = [taskCategories indexOfObject:self.currentCategory];
    if (catIndex == indexPath.row) {
        return;
    }
    NSIndexPath *oldIndexPath = [NSIndexPath indexPathForRow:catIndex inSection:0];

    UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
    if (newCell.accessoryType == UITableViewCellAccessoryNone) {
        newCell.accessoryType = UITableViewCellAccessoryCheckmark;
        self.currentCategory = [taskCategories objectAtIndex:indexPath.row];
    }

    UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:oldIndexPath];
    if (oldCell.accessoryType == UITableViewCellAccessoryCheckmark) {
        oldCell.accessoryType = UITableViewCellAccessoryNone;
    }
}

Ответы [ 2 ]

1 голос
/ 08 апреля 2011

Там есть одна или две недостающие части.Из того, что я вижу, вам нужно поместить

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

вверху файла, в котором находится код, прежде чем он запустится, а затем объявить в классе пару переменных экземпляра:

@interface myClass
{
  MyCustomCategoryClass *currentCategory; // pointer to the currently checked item
  NSArray *taskCategories; // pointer to an array of your list items
      ... // other instance variables here
}

    ... // other @property declarations here or in your .m file
@property (assign) MyCustomCategoryClass *currentCategory;
@property (retain) NSArray *taskCategories;

MyCustomCategoryClass может быть любым классом, который вам нравится, но это то, что выбирает ваш пользователь.это может быть просто NSString, если хотите.Я говорю assign для currentCategory, потому что на самом деле это не указатель с владельцем элемента, ссылка на владельца должна быть в массиве (который retain ed).Вы также можете сделать taskCategories @property(nonatomic, retain), но я бы, вероятно, оставил currentCategory как atomic (по умолчанию) на случай, если он находится в середине изменения, когда вы хотите прочитать то, что выбрал пользователь.

О, и не забудьте заполнить свои taskCategories элементами, прежде чем пользователь сможет выбирать из списка.

0 голосов
/ 05 января 2012
@property (nonatomic,retain) NSIndexPath *oldIndexPath;
@synthesize oldIndexPath;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];

   UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    if (cell.accessoryType == UITableViewCellAccessoryNone) {
        UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:self.oldIndexPath];
        if (oldCell.accessoryType == UITableViewCellAccessoryCheckmark) {
            oldCell.accessoryType = UITableViewCellAccessoryNone;
        }
        cell.accessoryType = UITableViewCellAccessoryCheckmark;

    self.oldIndexPath = indexPath;
} else if(cell.accessoryType == UITableViewCellAccessoryCheckmark){
    UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:self.oldIndexPath];
    if (oldCell.accessoryType == UITableViewCellAccessoryCheckmark) {
        oldCell.accessoryType = UITableViewCellAccessoryNone;
    }
    cell.accessoryType = UITableViewCellAccessoryNone;

    self.oldIndexPath = indexPath;
}//cell acctype

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...