iOS 开发中可能遇到的转换方法

2017-11-07  本文已影响9人  41c48b8df394

测试推送 工具 Easy APNs Provider

1.字符串拼接的三种

//1.截取字符串

NSString *string =@"123456d890";
NSString *str1 = [string substringToIndex:5];//截取掉下标5之前的字符串
NSLog(@"截取的值为:%@",str1);
 NSString *str2 = [string substringFromIndex:3];//截取掉下标3之后的字符串
NSLog(@"截取的值为:%@",str2);

//2.匹配字符串

NSString *string =@"sd是sfsfsAdfsdf";
NSRange range = [string rangeOfString:@"Ad"];//匹配得到的下标
NSLog(@"rang:%@",NSStringFromRange(range));
string = [string substringWithRange:range];//截取范围内的字符串
NSLog(@"截取的值为:%@",string);

//3.分隔字符串

NSString *string =@"sdfsfsfsAdfsdf";
    
NSArray *array = [string componentsSeparatedByString:@"A"]; //从字符A中分隔成2个元素的数组
NSLog(@"array:%@",array); //结果是adfsfsfs和dfsdf
2.iOS11 关于导航栏searchbar 的调整
    [[UISearchBar appearance] setSearchFieldBackgroundImage:[self searchFieldBackgroundImage] forState:UIControlStateNormal];
    UITextField *txfSearchField = [_searchChatRecords valueForKey:@"_searchField"];
    [txfSearchField setDefaultTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13.5]}];

调用方法

//调用方法
- (UIImage*)searchFieldBackgroundImage {
    UIColor*color = [UIColor whiteColor];
    CGFloat cornerRadius = 5;
    CGRect rect =CGRectMake(0,0,28,28);
    
    UIBezierPath*roundedRect = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];
    roundedRect.lineWidth=0;
    
    UIGraphicsBeginImageContextWithOptions(rect.size,NO,0.0f);
    [color setFill];
    [roundedRect fill];
    [roundedRect stroke];
    [roundedRect addClip];
    
    UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
3.关于时间转换成系统时区

北京时间与UTC时间相差8个小时,因此每次会转换成当前时间,这个方法是转换成系统时区的时间

- (NSTimeInterval)getNowDateWithDate:(NSDate *)date{
    NSTimeZone *zone = [NSTimeZone systemTimeZone]; // 获得系统的时区
    NSTimeInterval time = [zone secondsFromGMTForDate:date];// 以秒为单位返回当前时间与系统格林尼治时间的差
    NSDate *nowDate = [date dateByAddingTimeInterval:time];
    NSTimeInterval timeInterval = [nowDate timeIntervalSince1970];
    return timeInterval;
}
4.字符串UT-8编码 与解码

编码:
iOS9以前格式:

NSString*hStr =@"你好啊";

NSString*hString = [hStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSLog(@"hString === %@",hString);

iOS9 以后格式:

NSString*hString = [hStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

解码
iOS9之前:

NSString*str3 =@"\u5982\u4f55\u8054\u7cfb\u5ba2\u670d\u4eba\u5458\uff1f";

NSString*str5 = [str3 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSLog(@"str5 ==== %@",str5);

iOS9之后

NSString*str5 = [str3 stringByRemovingPercentEncoding];
上一篇下一篇

猜你喜欢

热点阅读