Search code examples
iosobjective-ctttattritubedlabel

How to make TTTAttributedLabel align center programatically in IOS


I am developing an app where I have a string that consists of tags with prefix #.

I am using TTTAttribute Label to add links to words which are having prefix # in a given string.

When I added links to TTTAttribute label. It successfully added and when clicking on that I am able to get that selected word having prefix # in that string..

But I was not able to align center the TTTAttribute label based on string length..

The default property

attributedLabel.verticalAlignment=TTTAttributedLabelVerticalAlignmentCenter;

is not working while applying links..I want the label align center based on its length as shown below..

Label with single tag

Label with two tags

Label with three tags

If it is normal TTTAttribute label without applying links then default align property is applying correctly..

Here is the code I used for adding links..

 - (void)viewDidLoad
    {
        [super viewDidLoad];
        NSRange matchRange;
        NSString *tweet = @"#MYTWEET ,#tweet, #fashion #Share";

        NSScanner *scanner = [NSScanner scannerWithString:tweet];
        if (![scanner scanUpToString:@"#" intoString:nil]) {
            // there is no opening tag
        }
        NSString *result = nil;
        if (![scanner scanUpToString:@" " intoString:&result]) {
            // there is no closing tag
        }
        //@"theString is:%@",result);


        NSArray *words = [tweet componentsSeparatedByString:@" "];

      TTTAttributedLabel *attributedLabel=[[TTTAttributedLabel alloc]initWithFrame:CGRectMake(5, 200, 320, 40)];

      attributedLabel.textAlignment=NSTextAlignmentCenter;

        attributedLabel.text=tweet;

        words = [tweet componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@",0123456789`~!@$%^&*()_-+=.></?;:'* "]];

        for (NSString *word in words)
        {
            if ([word hasPrefix:@"#"])
            {
                //@"word %@",word);

                // Colour your 'word' here
                 matchRange=[tweet rangeOfString:word];

                [attributedLabel addLinkToURL:[NSURL URLWithString:word] withRange:matchRange];

                [tagsarray addObject:word];
            }

        }

        attributedLabel.delegate=self;

       }

    - (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url
    {
       //@"result ==== %@",url);

        NSString *webString=[NSString stringWithFormat:@"%@",url];

        NSString *tagstring = [webString stringByReplacingOccurrencesOfString:@"#" withString:@""];
        NSLog(@"Tag String is:%@",tagstring);

        }

I don't want to resize the frames of TTTAttribute label..

Any suggestions or help will be appreciated..

Thanks in Advance..


Solution

  • Its very simple, use the following code:

    attributedLabel.textAlignment = NSTextAlignmentCenter;