字符串

常规字符串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);

.
富文本

你可能感兴趣的:(字符串)