字符串

常规字符串NSString

字符串是否包含子串

// 利用range
[dateStr rangeOfString:@"an"].location == NSNotFound
// iOS 8.0 later
[dateStr containsString:@"an"];

判断只有数字、小数点和减号

#define NUMBERS @"0123456789.-"

#pragma mark -是否只包含数字,小数点,负号
- (BOOL)isOnlyhasNumberAndpointWithString:(NSString *)string
{
    NSCharacterSet *cs=[[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
    NSString *filter=[[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    return [string isEqualToString:filter];
}

字符串截取

  • [str substringWithRange:NSMakeRange(m,n)] 从第m个开始截取n个
  • [str substringToIndex:n] 截取到第n个(n不在截取内)
  • [str substringFromIndex:n] 从第n个截取到末尾(包含n)

富文本NSMutableAttributedString

富文本属性

NSFontAttributeName : 字体,默认字体Helvetica(Neue) /字号12
NSForegroundColorAttributeNam : 字体颜色,取值为UIColor对象,默认黑色
NSBackgroundColorAttributeName : 字体区域背景色,取值为UIColor对象,默认nil,透明色
NSLigatureAttributeName : 连体属性,取值为NSNumber对象(整数),0没有连体字符,默认1连体字符
NSKernAttributeName : 字符间距,取值为NSNumber 对象(整数),正值间距加宽,负值变窄
NSStrikethroughStyleAttributeName : 删除线,取值为 NSNumber 对象(整数)
NSStrikethroughColorAttributeName : 删除线颜色,取值为UIColor对象,默认黑色
NSUnderlineStyleAttributeName : 下划线,取值为枚举NSUnderlineStyle中的值,与删除线类似
NSUnderlineColorAttributeName : 下划线颜色,取值为UIColor 对象,默认黑色
NSStrokeWidthAttributeName : 笔画宽度,取值为NSNumber 对象(整数),负值填充效果,正值中空效果
NSStrokeColorAttributeName : 填充部分颜色,不是字体颜色,取值为UIColor 对象
NSShadowAttributeName : 阴影属性,取值为NSShadow对象
NSTextEffectAttributeName : 文本特殊效果,取值为NSString对象,目前只有图版印刷效果可用:
NSBaselineOffsetAttributeName : 基线偏移值,取值为NSNumber(float),正值上偏,负值下偏
NSObliquenessAttributeName : 字形倾斜度,取值为NSNumber(float),正值右倾,负值左倾
NSExpansionAttributeName : 文本横向拉伸属性,取值为NSNumber(float),正值横向拉伸文本,负值横向压缩文本
NSWritingDirectionAttributeName : 文字书写方向,从左向右书写或者从右向左书写
NSVerticalGlyphFormAttributeName : 文字排版方向,取值为NSNumber对象(整数),0表示横排文本,1表示竖排文本
NSLinkAttributeName : 链接属性,点击后调用浏览器打开指定URL地址
NSAttachmentAttributeName : 文本附件,取值为NSTextAttachment对象,常用于文字图片混排
NSParagraphStyleAttributeName : 文本段落排版格式,取值为NSParagraphStyle对象



NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:str];
    //格式调整
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    /**调行间距*/
    style.lineSpacing = 10;

    //字间距
    [attStr addAttribute:NSKernAttributeName value:@5 range:NSMakeRange(0, [str length])];
    //添加行间距
    [attStr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, [str length])];

    //横竖排版 ---无效果
//    [attStr addAttribute:NSVerticalGlyphFormAttributeName value:@1 range:NSMakeRange(0, [str length])];
    //下画线
    [attStr addAttribute:NSUnderlineStyleAttributeName value:@1 range:NSMakeRange(0, [str length])];
    //边线宽度
    [attStr addAttribute:NSStrokeWidthAttributeName value:@1 range:NSMakeRange(10, 10)];
    //边线颜色
    [attStr addAttribute:NSStrokeColorAttributeName value:[UIColor redColor] range:NSMakeRange(10, 10)];

    //阴影--无效果
    [attStr addAttribute:NSShadowAttributeName value:@4 range:NSMakeRange(20, 10)];

        //下划线
    [attStr addAttribute:NSStrikethroughStyleAttributeName value:@2 range:NSMakeRange(20, 10)];
    [attStr addAttribute:NSStrikethroughColorAttributeName value:[UIColor redColor] range:NSMakeRange(20, 10)];

    //字体背影色
    [attStr addAttribute:NSBackgroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(45, 10)];

    //字体颜色
    [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(60, 10)];

    //段落
    [attStr addAttribute:NSParagraphStyleAttributeName value:@6 range:NSMakeRange(70, 80)];

详见1
详见2

富文本计算高度

#pragma mark 文字高度
- (CGFloat)textH:(NSString *)text lineSpace:(CGFloat)lineSpace width:(CGFloat)width font:(UIFont *)font
{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineSpacing = lineSpace;
    NSDictionary *attributes = @{NSParagraphStyleAttributeName:paragraphStyle,NSFontAttributeName:font};
    CGSize size = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:attributes
                                     context:nil].size;
    return size.height;
}

改变子串颜色

+ (__kindof NSMutableAttributedString *_Nonnull)changeTotalString:(NSString *_Nonnull)totalString subStringArray:(NSArray *_Nonnull)subStringArray subStringColor:(UIColor *_Nonnull)color andFont:(UIFont *_Nonnull)font {
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:totalString];
    for (NSString *rangeStr in subStringArray) {
        NSRange range = [totalString rangeOfString:rangeStr options:NSBackwardsSearch];
        [attributedStr addAttribute:NSForegroundColorAttributeName value:color range:range];
        [attributedStr addAttribute:NSFontAttributeName value:font range:range];
    }
    return attributedStr;
}

字符串中添加图片

- (NSAttributedString *)stringWithUIImage:(NSString *) contentStr {
    // 创建一个富文本
    NSMutableAttributedString * attriStr = [[NSMutableAttributedString alloc] initWithString:contentStr];
    // 修改富文本中的不同文字的样式
    [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 5)];
    [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, 5)];

    /**
     添加图片到指定的位置
     */
    NSTextAttachment *attchImage = [[NSTextAttachment alloc] init];
    // 表情图片
    attchImage.image = [UIImage imageNamed:@"jiedu"];
    // 设置图片大小
    attchImage.bounds = CGRectMake(0, 0, 40, 15);
    NSAttributedString *stringImage = [NSAttributedString attributedStringWithAttachment:attchImage];
    [attriStr insertAttributedString:stringImage atIndex:2];

    // 设置数字为红色
    /*
    [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(5, 9)];
    [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(5, 9)];
    */
    //NSDictionary * attrDict = @{ NSFontAttributeName: [UIFont fontWithName: @"Zapfino" size: 15],
                               // NSForegroundColorAttributeName: [UIColor blueColor] };

    //创建 NSAttributedString 并赋值
    //_label02.attributedText = [[NSAttributedString alloc] initWithString: originStr attributes: attrDict];
    NSDictionary * attriBute = @{NSForegroundColorAttributeName:[UIColor redColor],NSFontAttributeName:[UIFont systemFontOfSize:30]};
    [attriStr addAttributes:attriBute range:NSMakeRange(5, 9)];

    // 添加表情到最后一位
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
    // 表情图片
    attch.image = [UIImage imageNamed:@"jiedu"];
    // 设置图片大小
    attch.bounds = CGRectMake(0, 0, 40, 15);

    // 创建带有图片的富文本
    NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
    [attriStr appendAttributedString:string];

    return attriStr;
}

段落

// paragraph style
    _style =  [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    _style.alignment = NSTextAlignmentLeft;  //对齐
    _style.headIndent = 0.0f;//行首缩进
    _style.firstLineHeadIndent = 10.0f;//首行缩进
    _style.tailIndent = 0.0f;//行尾缩进
    _style.lineSpacing = 2.0f;//行间距


    NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:_text attributes:@{ NSParagraphStyleAttributeName : _style}];
    
    UILabel *_content = [[UILabel alloc] init];
    _content.attributedText = attrText;

URL中含中文的解决

// 方法1:
NSString* encodedString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// 方法2:
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)urlString,NULL,NULL,kCFStringEncodingUTF8);

如果URL含有已转义的%等符号时,会再次转义而导致错误.

查看方法2参数说明:

CFStringRef CFURLCreateStringByAddingPercentEscapes(CFAllocatorRef allocator,CFStringRef originalString, CFStringRef charactersToLeaveUnescaped, CFStringRef legalURLCharactersToBeEscaped,CFStringEncoding encoding);

因此做出修改,写出方法:

NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlString, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]", NULL, kCFStringEncodingUTF8);

.
富文本

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,783评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,360评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,942评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,507评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,324评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,299评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,685评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,358评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,652评论 1 293
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,704评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,465评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,318评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,711评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,991评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,265评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,661评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,864评论 2 335

推荐阅读更多精彩内容