Friday, 19 December 2014

Attributed text in text view iOS

 NSArray *arrayName = @[@"Gaurav", @"Kunal", @"Madhvi",@"Ashu Sir",@"Gupta ji",@"Rajneesh",@"Vikram",@"Sakshi",@"Gaurav", @"Kunal", @"Madhvi",@"Ashu Sir",@"Gupta ji",@"Rajneesh",@"Vikram",@"Sakshi",@"Gaurav", @"Kunal", @"Madhvi",@"Ashu Sir",@"Gupta ji",@"Rajneesh",@"Vikram",@"Sakshi",@"Gaurav", @"Kunal", @"Madhvi",@"Ashu Sir",@"Gupta ji",@"Rajneesh",@"Vikram",@"Sakshi"];
    

    NSMutableString *stringName = [NSMutableString new];
    for (NSString *name in arrayName) {
        [stringName appendFormat:@"%@, ",name];
    }
 
    NSMutableAttributedString *strAtributed =[[NSMutableAttributedString alloc] initWithString:stringName];
    
    NSUInteger startName = 0, lengthName = 0;
    BOOL toogle = true;
    for (NSString *name in arrayName) {
        lengthName = name.length;
        NSRange range = NSMakeRange(startName, lengthName);
        startName += lengthName + 2;
        
        if (toogle) {
            [strAtributed addAttribute:NSForegroundColorAttributeName
                                 value:[UIColor lightGrayColor]
                                 range:range];
        } else {
            [strAtributed addAttribute:NSForegroundColorAttributeName
                                 value:[UIColor redColor]
                                 range:range];
        }
        toogle = !toogle;
    }
    
    
    [txtView setAttributedText:strAtributed];
    [txtView setFont:[UIFont systemFontOfSize:20]];

No comments:

Post a Comment