Reputation: 993
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..
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..
Upvotes: 6
Views: 3096
Reputation: 2624
You need to set the link attributes with the paragraph style set:
NSMutableParagraphStyle* attributeStyle = [[NSMutableParagraphStyle alloc] init];
attributeStyle.alignment = NSTextAlignmentCenter;
NSDictionary *attributes = @{NSFontAttributeName:[UIFont fontWithName:@"Helvetica Neue" size:11], NSForegroundColorAttributeName:[UIColor colorWithRed:0.324 green:0.0 blue:0.580 alpha:1.0], NSParagraphStyleAttributeName:attributeStyle};
[self.atributedLabel setLinkAttributes:attributes];
Upvotes: 16
Reputation: 2634
Its very simple, use the following code:
attributedLabel.textAlignment = NSTextAlignmentCenter;
Upvotes: 2