iOS学习笔记
2015年开始写博客,最近发现简书的博客风格相当美好, 所以进行了迁移. 因为还是菜鸟, 大多是从网上学习来的经验, 特在此记录, 一为日后查询方便, 二为借此为以后可以写原创打基础. 2016年会不断充实这篇学习笔记, 也争取写一些自己的原创.
NSString改变颜色与大小
// text为整体字符串, rangeText为需要修改的字符串
NSRange range = [text rangeOfString:rangeText];
NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:text];
// 设置属性修改字体颜色UIColor与大小UIFont
[attribute addAttributes:@{NSForegroundColorAttributeName:color, NSFontAttributeName:font} range:range];
label.attributedText = attribute;
时间戳转换
NSString *timeStr = model.serverTime;
// 返回值一般有毫秒,忽略掉毫秒
timeStr = [timeStr substringToIndex:10];
NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:[timeStr doubleValue]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd HH:mm"];
// 转换后的时间字符串
NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
NSDateFormatter格式说明:
G: 公元时代,例如AD公元
yy: 年的后2位
yyyy: 完整年
MM: 月,显示为1-12
MMM: 月,显示为英文月份简写,如 Jan
MMMM: 月,显示为英文月份全称,如 Janualy
dd: 日,2位数表示,如02
d: 日,1-2位显示,如 2
EEE: 简写星期几,如Sun
EEEE: 全写星期几,如Sunday
aa: 上下午,AM/PM
H: 时,24小时制,0-23
K:时,12小时制,0-11
m: 分,1-2位
mm: 分,2位
s: 秒,1-2位
ss: 秒,2位
S: 毫秒
NSString过滤特殊字符
// 定义一个特殊字符的集合
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@/:;()¥「」"、[]{}#%-*+=_\\|~<>$€^•'@#$%^&*()_+'\""];
// 过滤字符串的特殊字符
NSString *newString = [trimString stringByTrimmingCharactersInSet:set];
深度遍历View的SubView
使用到的情景: 很多cell中有textfield, 现在需要在tableview滚动是取消所有的textfield的第一响应, 一个个写比较麻烦, 用一个递归方法, 用来遍历所有的子视图.
- (void)allView:(UIView *)rootView {
for (UIView *subView in [rootView subviews])
{
if (!rootView.subviews.count) {
return;
}
if ([subView isKindOfClass:[UITextField class]]) {
[(UITextField *)subView resignFirstResponder];
}
[self allView:subView];
}
}
iOS7后, 相机相册权限检查
// 相机权限
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
// 相册权限
// ALAuthorizationStatus authStatus = [ALAssetsLibrary authorizationStatus];
if (authStatus == AVAuthorizationStatusDenied || authStatus == AVAuthorizationStatusRestricted) {
// 相机不被允许或者被限制
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请在iPhone的“设置-隐私”选项中,允许该APP访问您的相机。" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
}
else if (authStatus == AVAuthorizationStatusNotDetermined) {
// 没有设置过权限, 会弹出询问窗口
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
if (granted) {
// 允许相机权限
// ...
}
}];
}
else if (authStatus == AVAuthorizationStatusAuthorized) {
// 允许使用相机
// ...
}
UIImageView的Image保存本地
点击方法:
- (IBAction)saveImageToAlbum:(id)sender {
UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
}
响应方法:
- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (!error) {
NSLog(@"保存成功");
}
else {
NSLog(@"保存失败");
}
}
ARC与MRC的混用
项目 | 目标库 | 方法 |
---|---|---|
MRC | ARC | 给需要采用ARC的文件添加-fobjc-arc选项 |
ARC | MRC | 给需要采用的MRC的文件添加-fno-objc-arc选项 |
NSArray快速求最大值 最小值 平均值 和
NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);
UITextField只能输入最多两位小数的数字规则
- (BOOL)validateNumber:(NSString*)string textField:(UITextField *)textField range:(NSRange)range {
if ([textField.text rangeOfString:@"."].location == NSNotFound) {
self.isHaveDian = NO;
}
if ([string length]>0) {
unichar single=[string characterAtIndex:0];
if ((single >= '0' && single<= '9') || single=='.') {
if(!textField.text.length){
if(single == '.') {
[textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
if (single == '0') {
[textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}
if (single == '.') {
if(!self.isHaveDian) {
self.isHaveDian=YES;
return YES;
}
else {
[textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}
else {
if (self.isHaveDian) {
NSRange ran=[textField.text rangeOfString:@"."];
int tt=range.location-ran.location;
if (tt <= 2) {
return YES;
}
else {
return NO;
}
}
else {
return YES;
}
}
}
else {
[textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}
else {
return YES;
}
}
解决xib的“Could not insert new outlet connection”问题
逐一排除下去应该会解决的:
-
检测.m文件“File inspector”界面的“Target Membership”中是否选上对应的target.
Target Membership - 把.h和.m文件
Remove Reference
后重新引用进工程. - 删除DeriveData目录, Xcode中选择
Windows-> Projects
点击delete
, 或者进入~/Library/Developer/XCode/DerivedData
手动删除.
Windows-> Projects
NSLog宏
#define NSLog(format, ...) do { \
fprintf(stderr, "<%s : %d> %s\n", \
[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], \
__LINE__, __func__); \
(NSLog)((format), ##__VA_ARGS__); \
fprintf(stderr, "-------\n"); \
} while (0)
输出格式为 <文件名 : 行数> -[类名 方法名]
<DTStat.m : 123> -[DTStat startAPP]
2016-04-08 16:58:03.408 TaoFang[3721:1852769] Cache Size:70
writeToFile遇到<null>时
在将NSDictionary格式保存到本地时, 本狼遇到value为<null>保存失败的问题, 现在解决方法是将NSDictionary转为NSData进行保存, 代码如下:
// dict转data保存本地
- (void)storeDataWithFileName:(NSString *)name data:(NSDictionary *)dic {
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:dic forKey:name];
[archiver finishEncoding];
NSString *docPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
NSString *plistPath = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", name]];
if (![data writeToFile:plistPath atomically:YES]) {
NSLog(@"%@数据缓存失败", name);
};
}
// 读取本地data转为dic
- (NSDictionary *)loadDataWithFileName:(NSString *)name {
NSString *docPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
NSString *plistPath = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", name]];
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:plistPath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *dic = [unarchiver decodeObjectForKey:name];
[unarchiver finishDecoding];
return dic;
}
关注豺狼的订阅号, 更新的新文章会第一时间收到通知~