如何在 IOS 中以编程方式使 TTTAttributedLabel 居中对齐

2024-04-27

我正在开发一个应用程序,其中有一个由带有前缀 # 的标签组成的字符串。

我正在使用 TTTAttribute Label 添加指向给定字符串中具有前缀 # 的单词的链接。

当我添加 TTTAttribute 标签的链接时。它已成功添加,当单击它时,我可以获取该字符串中具有前缀 # 的所选单词。

但我无法根据字符串长度将 TTTAttribute 标签居中对齐。

默认属性

attributeLabel.verticalAlignment=TTTAttributedLabelVerticalAlignmentCenter;

应用链接时不起作用。我希望标签根据其长度对齐中心,如下所示。

如果它是正常的 TTTAttribute 标签而不应用链接,则默认对齐属性应用正确。

这是我用于添加链接的代码..

 - (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);

        }

我不想调整 TTTAttribute 标签的框架大小。

任何建议或帮助将不胜感激。

提前致谢..


您需要使用段落样式设置来设置链接属性:

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];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 IOS 中以编程方式使 TTTAttributedLabel 居中对齐 的相关文章

随机推荐