2015-02-14 4 views
2

Я создаю рецепт приложения для ингредиентов. Когда я печатаю ингредиенты на текстовом поле, а затем нажимаю кнопку поиска, она загружает рецепты с этими типизированными ингредиентами, но на нем отображаются дополнительные ингредиенты на этикетке, и я хочу показать этикетку с типизированными ингредиентами разного цвета с дополнительные ингредиенты.Выделение текста TextField по-другому

пример кода:

-(void)drawTheCell:(Recipe *)recipeObject { 

    self.recipeTitle.text = recipeObject.title; 

    NSArray *dividesString = [recipeObject.ingredients componentsSeparatedByString:@", "]; 

    NSMutableString *listIngreditents; 
    for (int i=0; i < dividesString.count; i++) { 


     for(int j=0; i < recipeObject.keywords.count || j < i; j++) { 
     if ([dividesString objectAtIndex:i] == [recipeObject.keywords objectAtIndex:i]) { 
       self.recipeIngredients.text = [dividesString objectAtIndex:i]; 
       self.recipeIngredients.textColor = [UIColor greenColor]; 

       [listIngreditents appendString:self.recipeIngredients.text]; 
       NSLog(@"Found a match"); 

      } 
      else { 
        [listIngreditents appendString:[dividesString objectAtIndex:i]]; 
      } 
    } 

метка не отображает ингредиенты, но это не отображает рецепты без ингредиентов.

+0

Добро пожаловать в Переполнение стека! Пожалуйста, добавьте полезный код и описание проблемы здесь. Публикация [Минимальный, завершенный, проверенный пример] (http://stackoverflow.com/help/mcve), который демонстрирует вашу проблему, поможет вам получить более качественные ответы. Благодаря! –

+0

Каков рецепт «ключевые слова», используемый для внутреннего цикла? –

+0

«ключевые слова» являются объектами текстового поля, и я помещаю объекты внутри массива. – iloveios

ответ

1

Помимо того факта, что, как упоминал Фенелоуски, вы не используете приписанную строку, в вашей логике много проблем.

Ваш текущий внутренний цикл, вероятно, не будет делать то, что вы ожидаете, что делать ... В основном, внутренний цикл только собирается выполнить, когда либо индекс recipeObject меньше, чем текущий dividesString индекс или текущий dividesString индекс меньше, чем общее количество ключевых слов и, вообще говоря, с этой логикой вы в основном создали зависимости, которые не имеют смысла в том, что вы пытаетесь выполнить.

Вместо того, что вы хотите сделать, это увидеть текущие dividesString соответствует ли ваши любому ключевому слову в настоящее время в текстовом поле, поэтому, если хотел, чтобы кодировать логику вы пытаетесь с помощью двойной петли, вы могли бы перебрать все ключевые слова во время каждой итерации внешнего цикла и делать, если-иначе сравнение после внутреннего цикла завершения выполнения, например:

- (void)drawTheCell:(Recipe *)recipeObject { 

    self.recipeTitle.text = recipeObject.title; 

    // Break up the recipe ingredients into components 
    NSArray *dividesString = [recipeObject.ingredients componentsSeparatedByString:@", "]; 

    // Create a mutable attributed string so you can maintain 
    // color attributes 
    NSMutableAttributedString *listIngredients = [[NSMutableAttributedString alloc] init]; 

    // Loop through the ingredient components 
    for (int i=0; i < dividesString.count; i++) { 

     // Add a comma if it's not the first ingredient 
     if (i > 0) { 
      NSMutableAttributedString *commaString = [[NSMutableAttributedString alloc] initWithString:@", "]; 
      [listIngredients appendAttributedString:commaString]; 
     } 

     // Create a boolean to indicate whether a keyword match 
     // has been found 
     bool matchFound = NO; 

     // Loop through your "keywords" 
     for(int j=0; j < recipeObject.keywords.count; j++) { 

      // If the current ingredient matches the current keyword 
      // change the matchFound boolean to true 
      if ([[dividesString objectAtIndex:i] isEqualToString:[recipeObject.keywords objectAtIndex:j]]) { 
       matchFound = YES; 
       break; 
      } 
     } 

     NSMutableAttributedString *attString = 
       [[NSMutableAttributedString alloc] initWithString:[dividesString objectAtIndex:i]]; 

     if (matchFound) { 
      NSLog(@"Found a match"); 
      // Make the attributed string green 
      [attString addAttribute:NSForegroundColorAttributeName 
       value:[UIColor greenColor] 
       range:NSMakeRange(0, attString.length)]; 
      // Append the ingredient to listIngreditents 
      [listIngredients appendAttributedString:attString]; 
     } 
     else { 
      NSLog(@"Match not found"); 
      // Append the ingredient to listIngreditents 
      // with the default color 
      [listIngredients appendAttributedString:attString]; 
     } 
    } 

    // Set the label, ex. self.recipeIngredients.attributedText = listIngredients; 
} 

Но есть более простое решение - я рекомендую воздерживаясь внутренний цикл полностью и с помощью containsObject: чтобы увидеть, содержит ли массив recipeObject.keywords текущий компонент, например:

- (void)drawTheCell:(Recipe *)recipeObject { 

    self.recipeTitle.text = recipeObject.title; 

    // Break up the recipe ingredients into components 
    NSArray *dividesString = [recipeObject.ingredients componentsSeparatedByString:@", "]; 

    // Create a mutable attributed string so you can maintain 
    // color attributes 
    NSMutableAttributedString *listIngredients = [[NSMutableAttributedString alloc] init]; 

    // Loop through the ingredient components 
    for (int i=0; i < dividesString.count; i++) { 

     // Add a comma if it's not the first ingredient 
     if (i > 0) { 
      NSMutableAttributedString *commaString = [[NSMutableAttributedString alloc] initWithString:@", "]; 
      [listIngredients appendAttributedString:commaString]; 
     } 

     NSMutableAttributedString *attString = 
       [[NSMutableAttributedString alloc] initWithAttributedString:[dividesString objectAtIndex:i]]; 

     // If recipeObject.keywords contains the current 
     // ingredient, add the green attributed string 
     if([recipeObject.keywords containsObject:[dividesString objectAtIndex:i]]) { 
      NSLog(@"Found a match"); 
      // Make the attributed string green 
      [attString addAttribute:NSForegroundColorAttributeName 
       value:[UIColor greenColor] 
       range:NSMakeRange(0, attString.length)]; 
      // Append the ingredient to listIngreditents 
      [listIngredients appendAttributedString:attString]; 
     } 
     // Else, simply add the string 
     else { 
      NSLog(@"Match not found"); 
      // Append the ingredient to listIngreditents 
      // with the default color 
      [listIngredients appendAttributedString:attString]; 
     } 
    } 

    // Set the label, ex. self.recipeIngredients.attributedText = listIngredients; 
} 
+0

Большое вам спасибо! Вы потрясающе, и мне понравилось, как вы так объяснили!Единственное, что я получаю ошибку (нет visilbe @interface для NSAttributtedString) здесь: [attString addAttribute: NSForegroundColorAttributeName значение: [UIColor greenColor] диапазон: NSMakeRange (0, attString.length)]; – iloveios

+0

@iloveios Что говорит об ошибке? –

+0

Нет видимых @interface для NSAttributtedString – iloveios

0

Вы на правильном пути, но одна серьезная проблема, которая помешает вам иметь разные слова в разных цветах, заключается в том, что вы не используете NSMutableAttributedString. Каждый раз, когда вы хотите, чтобы слово было другого цвета, вам нужно добавить этот атрибут только в этот раздел строки.

Как только у вас есть отформатированная строка, вы должны установить myTextField.attributedText.