2015-06-22 2 views
1

У меня есть методы для рисования таблицы муравьиного насекомого. Я хочу изменить цвет для одного слова из каждого столбца, но я не знаю, как я могу это сделать. Может ли мне помочь, пожалуйста? Любая помощь будет оценена.Установить цвет CFAttributedStringRef

в моем приложении пользователь может выбрать некоторые атрибуты управления segmente ... Я хочу, чтобы экспортировать то, что он выбрал в формате PDF, как таблицы .so на каждой строке слово будет выбран

-(void)drawTableDataAt:(CGPoint)origin 
     withRowHeight:(int)rowHeight 
     andColumnWidth:(int)columnWidth 
      andRowCount:(int)numberOfRows 
     andColumnCount:(int)numberOfColumns 
{ 
    int padding = 1; 

    NSArray* headers = [NSArray arrayWithObjects:@"Grand", @"Taile ok", @"Petit", nil]; 
    NSArray* invoiceInfo1 = [NSArray arrayWithObjects:@"Extra", @"Bon", @"Ordi", nil]; 
    NSArray* invoiceInfo2 = [NSArray arrayWithObjects:@"Gras", @"Etat", @"Maigre", nil]; 
    NSArray* invoiceInfo3 = [NSArray arrayWithObjects:@"Cru", @"Propre", @"Sale", nil]; 
    NSArray* invoiceInfo4 = [NSArray arrayWithObjects:@"PLourd", @"PMoyen", @"PLeger", nil]; 
    NSArray* invoiceInfo5 = [NSArray arrayWithObjects:@"CSup", @"CEgal", @"CInf", nil]; 


    NSArray* allInfo = [NSArray arrayWithObjects:headers, invoiceInfo1, invoiceInfo2, invoiceInfo3, invoiceInfo4, invoiceInfo5,nil]; 

    for(int i = 0; i < [allInfo count]; i++) 
    { 
     NSArray* infoToDraw = [allInfo objectAtIndex:i]; 

     for (int j = 0; j < numberOfColumns; j++) 
     { 

      int newOriginX = origin.x + (j*columnWidth); 
      int newOriginY = origin.y + ((i+1)*rowHeight); 

      CGRect frame = CGRectMake(newOriginX + padding, newOriginY + padding, columnWidth, rowHeight); 


      [self drawText:[infoToDraw objectAtIndex:j] inFrame:frame]; 
     } 

    } 

} 

- (недействительными) DrawText: (NSString *) textToDraw в рамке считывания: (CGRect) frameRect {

CFStringRef stringRef = (__bridge CFStringRef)textToDraw; 
    // Prepare the text using a Core Text Framesetter 
    CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, stringRef, NULL); 
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText); 


    CGMutablePathRef framePath = CGPathCreateMutable(); 
    CGPathAddRect(framePath, NULL, frameRect); 

    // Get the frame that will do the rendering. 
    CFRange currentRange = CFRangeMake(0, 0); 
    CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL); 
    CGPathRelease(framePath); 

    // Get the graphics context. 
    CGContextRef currentContext = UIGraphicsGetCurrentContext(); 

    // Put the text matrix into a known state. This ensures 
    // that no old scaling factors are left in place. 
    CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity); 


    // Core Text draws from the bottom-left corner up, so flip 
    // the current transform prior to drawing. 
    CGContextTranslateCTM(currentContext, 0, frameRect.origin.y*2); 
    CGContextScaleCTM(currentContext, 1.0, -1.0); 

    // Draw the frame. 
    CTFrameDraw(frameRef, currentContext); 

    CGContextScaleCTM(currentContext, 1.0, -1.0); 
    CGContextTranslateCTM(currentContext, 0, (-1)*frameRect.origin.y*2); 


    CFRelease(frameRef); 
    CFRelease(stringRef); 
    CFRelease(framesetter); 
} 

enter image description here enter image description here

+0

Итак, один цвет за столбец или? –

+0

один цвет для одной ячейки от каждой строки. Например, я хочу сделать красные следующие ячейки: Grand, Bon, Gras, Sale, Pleger и CEgal. –

+0

Итак, в основном слово будет случайным и иметь заданный цвет? Будет ли этот список когда-либо изменяться? –

ответ

1

На основе комментариев по этому вопросу вы упомянули, что слова никогда не изменятся. Вы могли бы создать целую группу операторов if/else, проверяющих каждое слово, выбранное для каждого слова в массиве. Я поставил это как более эффективную альтернативу, и он, надеюсь, будет работать. Это может потребоваться некоторые настройки, или даже цикл, чтобы пройти через выбранные слова, но это следует надеяться поставить вас в правильном направлении:

//declare your textToDraw as a new NSString 
NSString *str = textToDraw; 
//Make an Array of the str by adding objects that are separated by whitespace 
NSArray *words = [str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
//create a BOOL to check if your selected word exists in the array 
BOOL wordExists = [words containsObject: @"%@", yourSelectedWord]; 

CTFramesetterRef framesetter = null; 

//if the word exists, make it red 
if(wordExists){ 

    NSUInteger indexOfTheString = [words indexOfObject: @"%@", yourSelectedWord]; 

    CFAttributedStringRef currentText = CFAttributedStringCreate(NULL,str, NULL); 

    [currentText addAttribute:NSForegroundColorAttributeName 
     value:[UIColor redColor] 
     range:NSMakeRange(indexOfTheString, yourSelectedWord.length)]; 

    framesetter = CTFramesetterCreateWithAttributedString(currentText); 

} 

Это будет соответствовать вашему выбранному слову найдено против нужного слова в массиве и выделить он красный.

+0

и это где должно быть реализовано? Извините, но это первый случай, когда я делаю что-то вроде этого :( –

+0

в вашем методе drawText. Я не пробовал это раньше, чтобы он мог немного поиграть, но в теории он должен работать. Думаю, вы, возможно, сделали свой макет немного сложнее, чем могло бы быть, но я надеюсь, что это сработает. –

+0

и ярлык где это? Потому что я не использую метки .... –

Смежные вопросы