YYKit 常见用法总结

一、YYLabel

强大的富文本显示功能,可根据文字的range随意添加点击事件




1 自动换行

    YYLabel  *yyLabel = [YYLabel new];
    yyLabel.numberOfLines = 0;

   //创建容器
    YYTextContainer *titleContarer = [YYTextContainer new];
    //限制宽度
    titleContarer.size = CGSizeMake([UIScreen mainScreen].bounds.size.width-40,CGFLOAT_MAX);
    //设置富文本
    NSMutableAttributedString  *resultAttr = [self getAttr:title];
    //根据容器和文本创建布局对象
    YYTextLayout *titleLayout = [YYTextLayout layoutWithContainer:titleContarer text:resultAttr];
    //得到文本高度
    CGFloat titleLabelHeight = titleLayout.textBoundingSize.height;
    //设置frame
    yyLabel.frame = CGRectMake(20,84,[UIScreen mainScreen].bounds.size.width-40,titleLabelHeight);

2 各种格式设置 


    //对齐方式 这里是 两边对齐
    resultAttr.alignment = NSTextAlignmentCenter;
    //设置行间距
    resultAttr.lineSpacing = 3;
    resultAttr.font = [UIFont systemFontOfSize:20];
    {
        NSRange range =  [attributedString rangeOfString:@"it was the worst of times"];
        [resultAttr setFont:[UIFont boldSystemFontOfSize:30] range:range];
    }
    
//描边
    {
        NSRange range =[attributedString rangeOfString:@"it was the age of wisdom"];
        //文字描边(空心字)默认黑色,必须设置width
        [resultAttr setStrokeColor:[UIColor orangeColor] range:range];
        [resultAttr setStrokeWidth:@(2) range:range];
    }

//划线
    {
        NSRange range = [attributedString rangeOfString:@"it was the age of foolishness, it was the season of light" options:NSCaseInsensitiveSearch];
        YYTextDecoration *decoration = [YYTextDecoration decorationWithStyle:YYTextLineStyleSingle
                                                                       width:@(1)
                                                                       color:[UIColor blueColor]];
        //删除样式
        [resultAttr setTextStrikethrough:decoration range:range];
        //下划线
        [resultAttr setTextUnderline:decoration range:range];
    }
    
//设置边框
    {
        NSRange range = [attributedString rangeOfString:@"这是最好的时代,这是最坏的时代" options:NSCaseInsensitiveSearch];
        //边框
        YYTextBorder *border = [YYTextBorder new];
        border.strokeColor = [UIColor redColor];
        border.strokeWidth = 4;
        border.lineStyle = YYTextLineStylePatternDashDotDot;
        border.cornerRadius = 1;
        border.insets = UIEdgeInsetsMake(0, -2, 0, -2);
        [resultAttr setTextBorder:border range:range];

    }
    
//设置阴影
    {
        NSRange range = [attributedString rangeOfString:@"这是智慧的时代,这是愚蠢的时代" options:NSCaseInsensitiveSearch];
        //阴影
        NSShadow *shadow = [[NSShadow alloc] init];
        [shadow setShadowColor:[UIColor redColor]];
        [shadow setShadowBlurRadius:1.0];
        [shadow setShadowOffset:CGSizeMake(2, 2)];
        [resultAttr setShadow:shadow range:range];
    }


3 高亮显示文本 点击交互事件

{
        NSRange range = [attributedString rangeOfString:@"这是希望之春,这是失望之冬" options:NSCaseInsensitiveSearch];
        YYTextBorder *border = [YYTextBorder new];
        border.cornerRadius = 50;
        border.insets = UIEdgeInsetsMake(0, -10, 0, -10);
        border.strokeWidth = 0.5;
        border.strokeColor = [UIColor yellowColor];
        border.lineStyle = YYTextLineStyleSingle;
        [resultAttr setTextBorder:border range:range];
        [resultAttr setTextBackgroundBorder:border range:range];
        [resultAttr setColor:[UIColor greenColor] range:range];

        YYTextBorder *highlightBorder = border.copy;
        highlightBorder.strokeWidth = 0;
        highlightBorder.strokeColor =  [UIColor purpleColor];
        highlightBorder.fillColor =  [UIColor purpleColor];
        
        YYTextHighlight *highlight = [YYTextHighlight new];
        [highlight setColor:[UIColor whiteColor]];
        [highlight setBackgroundBorder:highlightBorder ];
        highlight.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
            [self alertShow:[NSString stringWithFormat:@"Tap: %@",[text.string substringWithRange:range]]];
        };
        [resultAttr setTextHighlight:highlight range:range];
        
        
        // 点击复制
        [resultAttr setTextHighlightRange:[attributedString rangeOfString:@"450351763"]
                                    color:[UIColor greenColor]
                          backgroundColor:[UIColor whiteColor]
                                tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
                                    pboard.string = @"450351763";
                                    [self alertShow:@"复制成功"];
                            
                                }];
    }


4 图文混排 支持各种格式包括gif

{
        for (int i = 1; i<5; i++) {
            NSString *path;
            if(i == 4){
                path = [[NSBundle mainBundle] pathForScaledResource:[NSString stringWithFormat:@"%d",i] ofType:@"gif"];
            }else{
                path = [[NSBundle mainBundle] pathForScaledResource:[NSString stringWithFormat:@"%d",i] ofType:@"jpg"];
            }
            NSData *data = [NSData dataWithContentsOfFile:path];
            //修改表情大小
            YYImage *image = [YYImage imageWithData:data scale:3];
            image.preloadAllAnimatedImageFrames = YES;
            YYAnimatedImageView *imageView = [[YYAnimatedImageView alloc] initWithImage:image];
            NSMutableAttributedString *attachText = [NSMutableAttributedString attachmentStringWithContent:imageView contentMode:UIViewContentModeCenter attachmentSize:imageView.size alignToFont:[UIFont systemFontOfSize:18] alignment:YYTextVerticalAlignmentCenter];
            [resultAttr appendAttributedString:attachText];
        }
    }


 

YYkit推荐pod安装方式(我使用的是  pod 'YYKit', '~> 1.0.9' 最新版本)

以下为全部代码贴到项目中可以直接运行查看效果

#import <YYKit/YYKit.h>

@interface ViewController2 ()

@end
@implementation ViewController2

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.3 green:0.5 blue:0.8 alpha:1];
    
    [self showYYLabel];
}
-(void)showYYLabel{
    NSString *title = @"It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the season of light, it was the season of darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us. We were all going direct to heaven, we were all going direct the other way.\n这是最好的时代,这是最坏的时代;这是智慧的时代,这是愚蠢的时代;这是信仰的时期,这是怀疑的时期;这是光明的季节,这是黑暗的季节;这是希望之春,这是失望之冬;人们面前有着各样事物,人们面前一无所有;人们正在直登天堂,人们正在直下地狱。\n点击复制QQ450351763进行在线咨询";
    YYLabel  *yyLabel = [YYLabel new];
    yyLabel.backgroundColor = [UIColor colorWithRed:0.3 green:0.4 blue:0.1 alpha:1];
    //异步显示
    yyLabel.displaysAsynchronously = YES;
    yyLabel.numberOfLines = 0;
    //创建容器
    YYTextContainer *titleContarer = [YYTextContainer new];
    //限制宽度
    titleContarer.size = CGSizeMake([UIScreen mainScreen].bounds.size.width-40,CGFLOAT_MAX);
    //设置富文本
    NSMutableAttributedString  *resultAttr = [self getAttr:title];
    //根据容器和文本创建布局对象
    YYTextLayout *titleLayout = [YYTextLayout layoutWithContainer:titleContarer text:resultAttr];
    //得到文本高度
    CGFloat titleLabelHeight = titleLayout.textBoundingSize.height;
    //设置frame
    yyLabel.frame = CGRectMake(20,84,[UIScreen mainScreen].bounds.size.width-40,titleLabelHeight);
    yyLabel.attributedText = titleAttr;
    [self.view addSubview:yyLabel];
}
- (NSMutableAttributedString*)getAttr:(NSString*)attributedString {
    NSMutableAttributedString *resultAttr = [[NSMutableAttributedString alloc] initWithString:attributedString];

//    一、 格式设置
    //对齐方式 这里是 两边对齐
    resultAttr.alignment = NSTextAlignmentCenter;
    //设置行间距
    resultAttr.lineSpacing = 3;
    resultAttr.font = [UIFont systemFontOfSize:20];
    {
        NSRange range =  [attributedString rangeOfString:@"it was the worst of times"];
        [resultAttr setFont:[UIFont boldSystemFontOfSize:30] range:range];
    }
    
//描边
    {
        NSRange range =[attributedString rangeOfString:@"it was the age of wisdom"];
        //文字描边(空心字)默认黑色,必须设置width
        [resultAttr setStrokeColor:[UIColor orangeColor] range:range];
        [resultAttr setStrokeWidth:@(2) range:range];
    }

//划线
    {
        NSRange range = [attributedString rangeOfString:@"it was the age of foolishness, it was the season of light" options:NSCaseInsensitiveSearch];
        YYTextDecoration *decoration = [YYTextDecoration decorationWithStyle:YYTextLineStyleSingle
                                                                       width:@(1)
                                                                       color:[UIColor blueColor]];
        //删除样式
        [resultAttr setTextStrikethrough:decoration range:range];
        //下划线
        [resultAttr setTextUnderline:decoration range:range];
    }
    
//设置边框
    {
        NSRange range = [attributedString rangeOfString:@"这是最好的时代,这是最坏的时代" options:NSCaseInsensitiveSearch];
        //边框
        YYTextBorder *border = [YYTextBorder new];
        border.strokeColor = [UIColor redColor];
        border.strokeWidth = 4;
        border.lineStyle = YYTextLineStylePatternDashDotDot;
        border.cornerRadius = 1;
        border.insets = UIEdgeInsetsMake(0, -2, 0, -2);
        [resultAttr setTextBorder:border range:range];

    }
    
//设置阴影
    {
        NSRange range = [attributedString rangeOfString:@"这是智慧的时代,这是愚蠢的时代" options:NSCaseInsensitiveSearch];
        //阴影
        NSShadow *shadow = [[NSShadow alloc] init];
        [shadow setShadowColor:[UIColor redColor]];
        [shadow setShadowBlurRadius:1.0];
        [shadow setShadowOffset:CGSizeMake(2, 2)];
        [resultAttr setShadow:shadow range:range];
    }
    

//高亮显示文本
    {
        NSRange range = [attributedString rangeOfString:@"这是希望之春,这是失望之冬" options:NSCaseInsensitiveSearch];
        YYTextBorder *border = [YYTextBorder new];
        border.cornerRadius = 50;
        border.insets = UIEdgeInsetsMake(0, -10, 0, -10);
        border.strokeWidth = 0.5;
        border.strokeColor = [UIColor yellowColor];
        border.lineStyle = YYTextLineStyleSingle;
        [resultAttr setTextBorder:border range:range];
        [resultAttr setTextBackgroundBorder:border range:range];
        [resultAttr setColor:[UIColor greenColor] range:range];

        YYTextBorder *highlightBorder = border.copy;
        highlightBorder.strokeWidth = 0;
        highlightBorder.strokeColor =  [UIColor purpleColor];
        highlightBorder.fillColor =  [UIColor purpleColor];
        
        YYTextHighlight *highlight = [YYTextHighlight new];
        [highlight setColor:[UIColor whiteColor]];
        [highlight setBackgroundBorder:highlightBorder ];
        highlight.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
            [self alertShow:[NSString stringWithFormat:@"Tap: %@",[text.string substringWithRange:range]]];
        };
        [resultAttr setTextHighlight:highlight range:range];
        
        
        // 点击复制
        [resultAttr setTextHighlightRange:[attributedString rangeOfString:@"450351763"]
                                    color:[UIColor greenColor]
                          backgroundColor:[UIColor whiteColor]
                                tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
                                    pboard.string = @"450351763";
                                    [self alertShow:@"复制成功"];
                            
                                }];
    }

    
    
//    图文混排
    {
        for (int i = 1; i<5; i++) {
            NSString *path;
            if(i == 4){
                path = [[NSBundle mainBundle] pathForScaledResource:[NSString stringWithFormat:@"%d",i] ofType:@"gif"];
            }else{
                path = [[NSBundle mainBundle] pathForScaledResource:[NSString stringWithFormat:@"%d",i] ofType:@"jpg"];
            }
            NSData *data = [NSData dataWithContentsOfFile:path];
            //修改表情大小
            YYImage *image = [YYImage imageWithData:data scale:3];
            image.preloadAllAnimatedImageFrames = YES;
            YYAnimatedImageView *imageView = [[YYAnimatedImageView alloc] initWithImage:image];
            NSMutableAttributedString *attachText = [NSMutableAttributedString attachmentStringWithContent:imageView contentMode:UIViewContentModeCenter attachmentSize:imageView.size alignToFont:[UIFont systemFontOfSize:18] alignment:YYTextVerticalAlignmentCenter];
            [resultAttr appendAttributedString:attachText];
        }
    }
  
    
    return resultAttr;
}

-(void)alertShow:(NSString *)str{
    UIAlertController *vc =  [UIAlertController alertControllerWithTitle:nil message:str preferredStyle:UIAlertControllerStyleActionSheet];
    [self.navigationController presentViewController:vc animated:YES completion:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [vc dismissViewControllerAnimated:YES completion:^{
                
            }];
        });
    }];
}

以后会陆续更新YYkit其他框架



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 iOS 中,可以使用 YYLabel 来显示富文本,包括 HTML 格式的富文本。YYLabel 是由 YYKit 提供的一个组件,它支持更多的文本属性设置,包括字体、颜色、行间距、字间距等等。 要在 YYLabel 中加载 HTML 富文本,可以使用 NSAttributedString 的 initWithData:options:documentAttributes:error: 方法来实现。具体步骤如下: 1. 将 HTML 字符串转换为 NSData 对象,可以使用 NSString 的 dataUsingEncoding: 方法来实现。 2. 使用 NSAttributedString 的 initWithData:options:documentAttributes:error: 方法,将 NSData 对象转换为 NSAttributedString 对象。 3. 将 NSAttributedString 对象赋值给 YYLabel 的 attributedText 属性,即可在 YYLabel 中显示 HTML 富文本。 下面是一个示例代码: ``` NSString *htmlString = @"<p>This is a <strong>bold</strong> text.</p>"; NSData *htmlData = [htmlString dataUsingEncoding:NSUTF8StringEncoding]; NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:htmlData options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil]; YYLabel *label = [[YYLabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)]; label.attributedText = attributedString; [self.view addSubview:label]; ``` 上面的代码中,我们首先将 HTML 字符串转换为 NSData 对象,然后使用 NSAttributedString 的 initWithData:options:documentAttributes:error: 方法将其转换为 NSAttributedString 对象。最后,我们将 NSAttributedString 对象赋值给 YYLabel 的 attributedText 属性,即可在 YYLabel 中显示 HTML 富文本。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值