UITableView повторяющиеся галочки - PullRequest
0 голосов
/ 22 октября 2011

У меня есть UITableView, который содержит список стран, где пользователь может выбрать несколько ячеек.Однако, когда я нажимаю на ячейку, каждая восьмая ячейка также ставит галочку рядом с ней!Я понятия не имею, почему это происходит, и это просто галочка.Код, прикрепленный к восьмой ячейке, не запускается, так что это просто визуальная вещь.Пожалуйста помоги!Вот мой код для didSelectRow таблицы:

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

    UITableViewCell *selectedCell = [tableView1 cellForRowAtIndexPath:indexPath];

    if ([selectedCell accessoryType] == UITableViewCellAccessoryNone) {
        [selectedCell setAccessoryType:UITableViewCellAccessoryCheckmark];
        int selectedRow = indexPath.row;
        NSString *intString = [NSString stringWithFormat:@"%d", selectedRow];
        if ([intString isEqualToString: @"0"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                 countriesselected = [countriestill stringByAppendingString:@"AR"];
            }
            else {
            countriesselected = [countriestill stringByAppendingString:@"-AR"];
        }
        }
        if ([intString isEqualToString: @"1"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"AU"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-AU"];
            }
        }
        if ([intString isEqualToString: @"2"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"BR"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-BR"];
            }
        }
        if ([intString isEqualToString: @"3"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"CA"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-CA"];
            }
        }
        if ([intString isEqualToString: @"4"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"CZ"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-CZ"];
            }
        }
        if ([intString isEqualToString: @"5"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"FR"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-FR"];
            }
        }
        if ([intString isEqualToString: @"6"] ) {
            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"DE"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-DE"];
            }
        }
        if ([intString isEqualToString: @"7"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"GB"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-GB"];
            }
        }
        if ([intString isEqualToString: @"8"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"HK"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-HK"];
            }
        }
        if ([intString isEqualToString: @"9"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"IN"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-IN"];
            }
        }
        if ([intString isEqualToString: @"10"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"IE"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-IE"];
            }
        }
        if ([intString isEqualToString: @"11"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"IL"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-IL"];
            }
        }
        if ([intString isEqualToString: @"12"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"IT"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-IT"];
            }
        }
        if ([intString isEqualToString: @"13"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"JP"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-JP"];
            }
        }
        if ([intString isEqualToString: @"14"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"MX"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-MX"];
            }
        }
        if ([intString isEqualToString: @"15"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"NL"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-NL"];
            }
        }
        if ([intString isEqualToString: @"16"] ) {
                     NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"NZ"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-NZ"];
            }
        }
        if ([intString isEqualToString: @"17"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"PL"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-PL"];
            }
        }
        if ([intString isEqualToString: @"18"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"RU"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-RU"];
            }
        }
        if ([intString isEqualToString: @"19"] ) {
            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"ZA"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-ZA"];
            }
        }
        if ([intString isEqualToString: @"20"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"KR"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-KR"];
            }
        }
        if ([intString isEqualToString: @"21"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"ES"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-ES"];
            }
        }
        if ([intString isEqualToString: @"22"] ) {
            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"SE"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-SE"];
            }
        }
        if ([intString isEqualToString: @"23"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"TW"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-TW"];
            }
        }
        if ([intString isEqualToString: @"24"] ) {

            NSString *countriestill = countriesselected;
            if ([countriesselected length] == 0) {
                countriesselected = [countriestill stringByAppendingString:@"US"];
            }
            else {
                countriesselected = [countriestill stringByAppendingString:@"-US"];
            }
        }

    }
    else {
        [selectedCell setAccessoryType:UITableViewCellAccessoryNone];
        int selectedRow = indexPath.row;
        NSString *intString = [NSString stringWithFormat:@"%d", selectedRow];
        if ([intString isEqualToString: @"0"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-AR"
                                                 withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"AR-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"AR"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"1"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-AU"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"AU-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"AU"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"2"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-BR"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"BR-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"BR"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"3"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-CA"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"CA-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"CA"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"4"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-CZ"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"CZ-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"CZ"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"5"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-FR"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"FR-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"FR"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"6"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-DE"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"DE-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"DE"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"7"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-GB"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"GB-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"GB"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"8"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-HK"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"HK-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"HK"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"9"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-IN"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"IN-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"IN"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"10"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-IE"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"IE-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"IE"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"11"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-IL"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"IL-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"IL"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"12"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-IT"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"IT-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"IT"
                                                                             withString:@""];
        }
        if ([intString isEqualToString: @"13"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-JP"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"JP-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"JP"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"14"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-MX"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"MX-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"MX"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"15"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-NL"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"NL-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"NL"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"16"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-NZ"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"NZ-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"NZ"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"17"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-PL"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"PL-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"PL"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"18"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-RU"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"RU-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"RU"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"19"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-ZA"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"ZA-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"ZA"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"20"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-KR"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"KR-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"KR"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"21"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-ES"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"ES-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"ES"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"22"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-SE"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"SE-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"SE"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"23"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-TW"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"TW-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"TW"
                                                                             withString:@""];

        }
        if ([intString isEqualToString: @"24"] ) {
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"-US"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"US-"
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:@"US"
                                                                             withString:@""];


        }
    }
    [tableView deselectRowAtIndexPath:indexPath animated:NO];


}

Ответы [ 2 ]

2 голосов
/ 23 октября 2011

Если вы не знакомы со словом «рефакторинг», это означает (в данном случае) избегать повторения себя в коде.Есть несколько очень хороших учебных пособий о «СУХОМ программировании» онлайн.В качестве примера, не изменяя ничего в вашей программе, ниже ваш код в 30 строк против 500+ строк.Помимо того, что вы короче, это также означает, что если вы вносите изменение, вам нужно сделать его только один раз, а не 24 или 48 раз.В конце концов, вам будет намного легче увидеть, что вы делаете.

В частности, я согласен с trydis, что ваша проблема, конечно, не в этом коде, а в вашем cellForRowAtIndexPath.После того, как вы извлекаете ячейку из очереди или создаете ее, [cell setAccessoryType: UITableViewCellAccessoryNone] В противном случае у ячеек без очереди будет тот аксессуар, который был в этой ячейке, когда он исчез с экрана.Восемь, вероятно, происходит из-за наличия восьми ячеек на экране одновременно, поэтому проверенная ячейка исчезает сверху и «появляется» внизу.

В качестве последнего комментария построение строки кода страны в реальном временинемного некрасиво (отсюда и все о дефисах).Возможно, лучше сохранить список активных кодов в NSMutableSet, а затем добавить дефисы, когда вы собираетесь его отобразить.([[countrySelected allObjects] componentJoinedByString @ "-"]

    NSArray * countryCodes = 
    [NSArray arrayWithObjects:@"AR",@"AU",@"BR",@"CA",@"CZ",@"FR",@"DE",@"GB",@"HK",@"IN",@"IE",@"IL",@"IT",
     @"JP",@"MX",@"NL",@"NZ",@"PL",@"RU",@"ZA",:@"KR",@"ES",@"SE",@"TW",@"US",nil];

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

    UITableViewCell *selectedCell = [tableView1 cellForRowAtIndexPath:indexPath];


    NSString *countryCode = [countryCodes objectAtIndex:indexPath.row];

    if ([selectedCell accessoryType] == UITableViewCellAccessoryNone) {
        [selectedCell setAccessoryType:UITableViewCellAccessoryCheckmark];
        if ([countriesselected length] == 0) {
            countriesselected = countryCode;
        } else {
            countriesselected = [NSString stringWithFormat:@"%@-%@",countriesselected,countryCode]];  // note change to include hyphen

        }

    } else {
        [selectedCell setAccessoryType:UITableViewCellAccessoryNone];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"-%@",countryCode]
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@-",countryCode]
                                                                             withString:@""];
            countriesselected = [countriesselected stringByReplacingOccurrencesOfString:countryCode"
                                                                             withString:@""];

    }
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

КОД ДЛЯ cellForRowAtIndePath:

 NSString *countryCode = [countryCodes objectAtIndex:indexPath.row];
 if ([countriesselected rangeOfString: countryCode].location != NSNotFound) {
     [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
 } else {
     [cell setAccessoryType:UITableViewCellAccessoryNone];
 }
1 голос
/ 23 октября 2011

Код остро нуждается в некотором рефакторинге, но я собираюсь выйти на конечность и предположить, что проблема вызвана повторным использованием ячеек.Используете ли вы dequeueReusableCellWithIdentifier в методе cellForRowAtIndexPath?Если это так, не забывайте устанавливать правильный тип accessoryType при каждом вызове, а не при создании ячейки.

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