如何在UILabel的内容较多时只显示3行的内容,在省略号后显示更多,点击更多添加点击的动作

如上述要求,我们可以给UILabel 添加一个类别方法,
@interface UILabel (ReadMore)

-(void)setReadMoreLabelContentMode;

@end

#import "UILabel+ReadMore.h"

#import <CoreText/CoreText.h>

@implementation UILabel (ReadMore)

-(void)setReadMoreLabelContentMode

{

    NSArray *contents = [self getLinesArrayOfLabelRows];

    if (contents.count <= 1) {

        self.userInteractionEnabled = NO; // 如果一行就不显示查看更多,同时取消手势响应

        return;

    }

    self.userInteractionEnabled=YES;

    

    NSUInteger cutLength = 7; // 截取的长度20

    

    NSMutableString *contentText = [[NSMutableString alloc] init];

    for (NSInteger i = 0; i < self.numberOfLines; i++) {

        if (i == self.numberOfLines - 1) { // 最后一行 进行处理加上.....

            

            NSString *lastLineText = [NSString stringWithFormat:@"%@",contents[i]];

            NSUInteger lineLength = lastLineText.length;

            if (lineLength > cutLength) {

                lastLineText = [lastLineText substringToIndex:(lastLineText.length - cutLength)];

            }

            [contentText appendString:[NSString stringWithFormat:@"%@.....",lastLineText]];

            

        } else {

            [contentText appendString:contents[i]];

        }

    }

    

    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];

    NSDictionary *dictionary = @{

                                 NSForegroundColorAttributeName : self.textColor,

                                 NSFontAttributeName : self.font,

                                 NSParagraphStyleAttributeName : style

                                 };

    

    NSMutableAttributedString *mutableAttribText = [[NSMutableAttributedString alloc] initWithString:[contentText stringByAppendingString:@"  更多"] attributes:dictionary];

    [mutableAttribText addAttributes:@{

                                       NSFontAttributeName : [UIFont boldSystemFontOfSize:16.0f],

                                       NSForegroundColorAttributeName : [UIColor blueColor]

                                       } range:NSMakeRange(contentText.length, 4)];

    self.attributedText = mutableAttribText;

}

// 获取 Label 每行内容 得到一个数组

- (NSArray *)getLinesArrayOfLabelRows

{

    CGFloat labelWidth = self.frame.size.width;

    

    NSString *text = [self text];

    UIFont *font = [self font];

    if (text == nil) {

        return nil;

    }

    CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([font fontName]), [font pointSize], NULL);

    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;

    [attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attStr.length)];

    [attStr addAttribute:(NSString *)kCTFontAttributeName

                   value:(__bridge  id)myFont

                   range:NSMakeRange(0, attStr.length)];

    CFRelease(myFont);

    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr);

    CGMutablePathRef path = CGPathCreateMutable();

    CGPathAddRect(path, NULL, CGRectMake(0,0,labelWidth,100000));

    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);

    NSArray *lines = ( NSArray *)CTFrameGetLines(frame);

    NSMutableArray *linesArray = [[NSMutableArray alloc]init];

    for (id line in lines) {

        CTLineRef lineRef = (__bridge  CTLineRef )line;

        CFRange lineRange = CTLineGetStringRange(lineRef);

        NSRange range = NSMakeRange(lineRange.location, lineRange.length);

        NSString *lineString = [text substringWithRange:range];

        CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr,

                                       lineRange,

                                       kCTKernAttributeName,

                                       (CFTypeRef)([NSNumber numberWithFloat:0.0]));

        CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr,

                                       lineRange,

                                       kCTKernAttributeName,

                                       (CFTypeRef)([NSNumber numberWithInt:0.0]));

        [linesArray addObject:lineString];

    }

    CGPathRelease(path);

    CFRelease(frame);

    CFRelease(frameSetter);

    return (NSArray *)linesArray;

}

@end

调用该方法的的代码:

- (void)viewDidLoad {

    [super viewDidLoad];

    

    NSString *context = @"当最后一行显示不全时,需求有时候需要改变省略号的位置,系统并未提供,张娜拉邀请我去她家里玩了一会,然后吃饭,看电视动词打次,然后将最后一行文字在指定的地方截断,再拼接省略号";

        NSLog(@" %lu ",(unsigned long)context.length);

        

        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 60.0f, self.view.frame.size.width - 20.0f, 70.0f)];

        label.font = [UIFont systemFontOfSize:16.0f];

        label.numberOfLines = 3;

        [self.view addSubview:label];

        

        UITapGestureRecognizer *labelTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(labelTouchUpInside)];

        [label addGestureRecognizer:labelTapGestureRecognizer];

        

        label.text = context;

        [label setReadMoreLabelContentMode];

}

-(void)labelTouchUpInside{

    NSLog(@"查看更多");

}

  • 21
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的示例代码,可以在 Unity 和 NGUI 中实现显示带多个网络图片的富文本: ```csharp using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using UnityEngine.UI; public class RichText : MonoBehaviour { public UILabel label; public UIGrid imagesGrid; public GameObject imagePrefab; private List<string> urls = new List<string>(); // 正则表达式匹配网络图片的链接 private static readonly Regex UrlRegex = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase); public void SetText(string text) { // 清空之前的图片 foreach (Transform child in imagesGrid.transform) { Destroy(child.gameObject); } // 获取所有网络图片的链接 urls.Clear(); MatchCollection matches = UrlRegex.Matches(text); foreach (Match match in matches) { string url = match.Value; if (url.EndsWith(".jpg") || url.EndsWith(".png")) { urls.Add(url); } } // 将所有网络图片添加到 imagesGrid 中 foreach (string url in urls) { GameObject imageObject = Instantiate(imagePrefab, imagesGrid.transform); StartCoroutine(LoadImage(url, imageObject.GetComponent<UITexture>())); } // 将文本内容设置到 label 上 label.text = text; } private IEnumerator LoadImage(string url, UITexture texture) { WWW www = new WWW(url); yield return www; if (www.error == null) { texture.mainTexture = www.texture; } else { Debug.LogError("Failed to load image: " + www.error); } } } ``` 使用方法: 1. 在 Unity 中创建一个 UI Root,添加一个 NGUI 的 Label 和 Grid。 2. 将 RichText 脚本挂载到 Label 上,将 imagesGrid 和 imagePrefab 拖拽到脚本对应的字段中。 3. 调用 `SetText()` 方法设置富文本内容即可,例如: ```csharp RichText richText = GetComponent<RichText>(); richText.SetText("这是一段带图片的富文本,<img src=\"http://example.com/image1.jpg\"> 和 <img src=\"http://example.com/image2.png\">"); ``` 这样,就可以在 NGUI 中实现显示带多个网络图片的富文本了。注意,这里使用了 HTML 标记 `<img>` 来指定图片的链接,这是一种常见的富文本格式。同时,也可以根据需要修改正则表达式来支持不同的富文本格式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值