iOS必备知识

1获取系统语言设置

NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];

NSArray *languages = [userDefault objectForKey:@"AppleLanguages"];

NSString *preferredLang = [languages objectAtIndex:0];

2缓存路径下文件大小

- (unsigned long long int) cacheFolderSize

{

NSFileManager *_manager = [NSFileManager defaultManager];

NSArray *_cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,

NSUserDomainMask, YES);

NSString *_cacheDirectory = [_cachePaths objectAtIndex:];

NSArray *_cacheFileList;

NSEnumerator *_cacheEnumerator;

NSString *_cacheFilePath;

unsigned long long int _cacheFolderSize = ;

_cacheFileList = [ _manager subpathsAtPath:_cacheDirectory];

_cacheEnumerator = [_cacheFileList objectEnumerator];

while (_cacheFilePath = [_cacheEnumerator nextObject])

{

NSDictionary *_cacheFileAttributes = [_managerfileAttributesAtPath:

[_cacheDirectory stringByAppendingPathComponent:_cacheFilePath]

traverseLink:YES];

_cacheFolderSize += [_cacheFileAttributes fileSize];

}

// 单位是字节

return _cacheFolderSize;

}

3Popover push 时 Frame无法改变解决办法

在popover中的ViewController中实现:

- (void)viewWillAppear:(BOOL)animated

{

CGSize size = CGSizeMake(320, 480); // size of view in popover

self.contentSizeForViewInPopover = size;

[super viewWillAppear:animated];

}

4SFHFKeychainUtils 存储信息

苹果SDK自带的就有密码保护,使用方法很简单,如下:

1、引入Security.frameWork框架。

2、引入头文件:SFHKeychainUtils.h.

3、存密码:

[SFHFKeychainUtils storeUsername:@"dd" andPassword:@"aa"forServiceName:SERVICE_NAMEupdateExisting:1 error:nil];

[SFHFKeychainUtils deleteItemForUsername:@"dd" andServiceName:SERVICE_NAME error:nil];

4、取密码:

NSString *passWord = [SFHFKeychainUtils getPasswordForUsername:@"dd"andServiceName:SERVICE_NAMEerror:nil];

5missing required architecture i386 in file 解决办法

在TargetInfo里面修改 Framework Search Pasths 删除里面内容就可以了。

6view 放大缩小动画效果

//创建缩小了的视图

myWeiBoImageVC = [[UIViewController alloc] init];

myWeiBoImageVC.view.clipsToBounds = YES;

myWeiBoImageVC.view.alpha = 0.0;

myWeiBoImageVC.view.frame = CGRectMake(64, 0, 1024-64, 768-20);

[self.view addSubview:myWeiBoImageVC.view];

CGAffineTransform newTransform =

CGAffineTransformScale(myWeiBoImageVC.view.transform, 0.1, 0.1);

[myWeiBoImageVC.view setTransform:newTransform];

myWeiBoImageVC.view.center = CGPointMake(670, 100);

[self performSelector:@selector(imageViewControllerBigAnimation)];

//放大刚刚创建缩小后的视图

- (void)imageViewControllerBigAnimation{

[UIView beginAnimations:@"imageViewBig" context:nil];

[UIView setAnimationDuration:0.5];

CGAffineTransform newTransform = CGAffineTransformConcat(myWeiBoImageVC.view.transform, CGAffineTransformInvert(myWeiBoImageVC.view.transform));

[myWeiBoImageVC.view setTransform:newTransform];

myWeiBoImageVC.view.alpha = 1.0;

myWeiBoImageVC.view.center = CGPointMake(416, 510);

[UIView commitAnimations];

}

//缩小视图 隐藏

- (void)imageViewControllerSmallAnimation{

[UIView beginAnimations:@"imageViewSmall" context:nil];

[UIView setAnimationDuration:0.5];

CGAffineTransform newTransform = CGAffineTransformScale(myWeiBoImageVC.view.transform, 0.1, 0.1);

[myWeiBoImageVC.view setTransform:newTransform];

myWeiBoImageVC.view.center = CGPointMake(670, 100);

[UIView commitAnimations];

}

7、给View添加阴影 和边框

UIImageView *imgvPhoto = [UIImageView alloc] init];

//添加边框

CALayer *layer = [_imgvPhoto layer];

layer.borderColor = [[UIColor whiteColor] CGColor];

layer.borderWidth = 5.0f;

//添加四个边阴影

_imgvPhoto.layer.shadowColor = [UIColor blackColor].CGColor;

_imgvPhoto.layer.shadowOffset = CGSizeMake(0, 0);

_imgvPhoto.layer.shadowOpacity = 0.5;

_imgvPhoto.layer.shadowRadius = 10.0;

//添加两个边阴影

_imgvPhoto.layer.shadowColor = [UIColor blackColor].CGColor;

_imgvPhoto.layer.shadowOffset = CGSizeMake(4, 4);

_imgvPhoto.layer.shadowOpacity = 0.5;

_imgvPhoto.layer.shadowRadius = 2.0;

8、使用NSTimer与UIView动画实现飘雪效果

viewDidLoad事件中,增加一个图片及定时器并启动,这里的pic请在头文件中定义。

-(void)viewDidLoad{

[super viewDidLoad];

self.pic = [UIImage imageNamed:@"snow.png"];//初始化图片

//启动定时器,实现飘雪效果

[NSTimer scheduledTimerWithTimeInterval:(0.2) target:self selector:@selector(ontime) userInfo:nil repeats:YES];

}

然后再实现定时器定时调用的ontime方法:

-(void)ontime{

UIImageView *view = [[UIImageView alloc] initWithImage:pic];//声明一个UIImageView对象,用来添加图片

view.alpha = 0.5;//设置该view的alpha为0.5,半透明的

int x = round(random()20);//随机得到该图片的x坐标

int y = round(random()20);//这个是该图片移动的最后坐标x轴的

int s = round(random())+10;//这个是定义雪花图片的大小

int sp = 1/round(random()0)+1;//这个是速度

view.frame = CGRectMake(x, -50, s, s);//雪花开始的大小和位置

[self.view addSubview:view];//添加该view

[UIView beginAnimations:nil context:view];//开始动画

[UIView setAnimationDuration:10*sp];//设定速度

view.frame = CGRectMake(y, 500, s, s);//设定该雪花最后的消失坐标

[UIView setAnimationDelegate:self];

[UIView commitAnimations];

}

9、ASIHTTPRequest实现断点下载

- (IBAction)URLFetchWithProgress:(id)sender

{

[startButton setTitle:@"Stop" forState:UIControlStateNormal];

[startButton addTarget:self action:@selector(stopURLFetchWithProgress:)forControlEvents:UIControlEventTouchUpInside];

NSString*tempFile = [[[[NSBundle mainBundle] bundlePath]stringByDeletingLastPathComponent]stringByAppendingPathComponent:@"MemexTrails_1.0b1.zip.download"];

if ([[NSFileManager defaultManager] fileExistsAtPath:tempFile]) {

[[NSFileManager defaultManager] removeItemAtPath:tempFile error:nil];

}

[self resumeURLFetchWithProgress:self];

}

- (IBAction)stopURLFetchWithProgress:(id)sender

{

networkQueue = [[ASINetworkQueue alloc] init];

timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:selfselector:@selector(updateBandwidthUsageIndicator) userInfo:nil repeats:YES];

timer = nil;

[startButton setTitle:@"Stop" forState:UIControlStateNormal];

[startButton addTarget:self action:@selector(URLFetchWithProgress:)forControlEvents:UIControlEventTouchUpInside];

[networkQueue cancelAllOperations];

[resumeButton setEnabled:YES];

}

- (IBAction)resumeURLFetchWithProgress:(id)sender

{

[resumeButton setEnabled:NO];

[startButton setTitle:@"Start" forState:UIControlStateNormal];

[startButton addTarget:self action:@selector(stopURLFetchWithProgress:)forControlEvents:UIControlEventTouchUpInside];

[networkQueue cancelAllOperations];

[networkQueue setShowAccurateProgress:YES];

[networkQueue setDownloadProgressDelegate:progressIndicator];

[networkQueue setDelegate:self];

[networkQueue setRequestDidFinishSelector:@selector(URLFetchWithProgressComplete:)];

ASIHTTPRequest*request=[[[ASIHTTPRequest alloc] initWithURL:[NSURLURLWithString:@"http://9991.net/blog/mp3/2.mp3"]] autorelease];

[request setDownloadDestinationPath:[[[[NSBundle mainBundle] bundlePath]

stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"MemexTrails_1.0b1.mp3"]];

[request setTemporaryFileDownloadPath:[[[[NSBundle mainBundle] bundlePath]stringByDeletingLastPathComponent]stringByAppendingPathComponent:@"MemexTrails_1.0b1.zip.down"]];

[request setAllowResumeForFileDownloads:YES];

[networkQueue addOperation:request];

[networkQueue go];

}

- (void)URLFetchWithProgressComplete:(ASIHTTPRequest *)request

{

if ([request error]) {

fileLocation.text=[NSString stringWithFormat:@"An error occurred:%@",[[[requesterror] userInfo] objectForKey:@"Title"]];

} else {

fileLocation.text=[NSString stringWithFormat:@"File downloaded to %@",[requestdownloadDestinationPath]];

}

[startButton setTitle:@"Start" forState:UIControlStateNormal];

[startButton addTarget:self action:@selector(URLFetchWithProgress:)forControlEvents:UIControlEventTouchUpInside];

}

- (IBAction)throttleBandwidth:(id)sender

{

if ([(UIButton *)sender state] ==YES) {

[ASIHTTPRequest setMaxBandwidthPerSecond:ASIWWANBandwidthThrottleAmount];

} else {

[ASIHTTPRequest setMaxBandwidthPerSecond:];

}

}

10、CoreText 总结

(1) NSAttributedString

NSAttributedString 可以将一段文字中的部分文字设置单独的字体和颜色。

与UITouch结合可以实现点击不同文字触发不同事件的交互功能。

主要方法:

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;

可以设置某段文字的字体名称,颜色,下滑线等信息。

- (void)removeAttribute:(NSString *)name range:(NSRange)range;

移除之前设置的字体属性值。

- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;

存储某段文字包含的信息(包括字体属性或其它,也可以存储一些自定义的信息)

- (NSDictionary *)attributesAtIndex:(NSUInteger)location effectiveRange:(NSRangePointer)range;

通过location来获取某段文字中之前存储的信息NSDictionary

//设置字体

CTFontRef aFont = CTFontCreateWithName((CFStringRef)textFont.fontName, textFont.pointSize, NULL);

if (!aFont) return;

CTFontRef newFont = CTFontCreateCopyWithSymbolicTraits(aFont, 0.0, NULL, kCTFontItalicTrait, kCTFontBoldTrait); //将默认黑体字设置为其它字体

[self removeAttribute:(NSString*)kCTFontAttributeName range:textRange];

[self addAttribute:(NSString*)kCTFontAttributeName value:(id)newFont range:textRange];

CFRelease(aFont);

CFRelease(newFont);

//设置字体颜色

[self removeAttribute:(NSString*)kCTForegroundColorAttributeName range:textRange];

[self addAttribute:(NSString*)kCTForegroundColorAttributeName value:(id)textColor.CGColor range:textRange];

//设置对齐 换行

CTTextAlignment coreTextAlign = kCTLeftTextAlignment;

CTLineBreakMode coreTextLBMode = kCTLineBreakByCharWrapping;

CTParagraphStyleSetting paraStyles[2] =

{

{.spec = kCTParagraphStyleSpecifierAlignment, .valueSize = sizeof(CTTextAlignment), .value = (const void*)&coreTextAlign},

{.spec = kCTParagraphStyleSpecifierLineBreakMode, .valueSize = sizeof(CTLineBreakMode), .value = (const void*)&coreTextLBMode},

};

CTParagraphStyleRef aStyle = CTParagraphStyleCreate(paraStyles, 2);

[self removeAttribute:(NSString*)kCTParagraphStyleAttributeName range:textRange];

[self addAttribute:(NSString*)kCTParagraphStyleAttributeName value:(id)aStyle range:textRange];

CFRelease(aStyle);

(2)Draw NSAttributedString

CGContextRef cgc = UIGraphicsGetCurrentContext();

CGContextSaveGState(cgc);

//图像方向转换

CGContextConcatCTM(cgc, CGAffineTransformScale(CGAffineTransformMakeTranslation(0, self.bounds.size.height), 1.f, -1.f));

CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)weiBoText);

drawingRect = self.bounds;

CGMutablePathRef path = CGPathCreateMutable();

CGPathAddRect(path, NULL, drawingRect);

textFrame = CTFramesetterCreateFrame(framesetter,CFRangeMake(0,0), path, NULL);

CGPathRelease(path);

CFRelease(framesetter);

CTFrameDraw(textFrame, cgc);

CGContextRestoreGState(cgc);

(3)图文混排

CTFrameRef textFrame // coreText 的 frame

CTLineRef line // coreText 的 line

CTRunRef run // line 中的部分文字

相关方法:

CFArrayRef CTFrameGetLines (CTFrameRef frame ) //获取包含CTLineRef的数组

void CTFrameGetLineOrigins(

CTFrameRef frame,

CFRange range,

CGPoint origins[] ) //获取所有CTLineRef的原点

CFRange CTLineGetStringRange (CTLineRef line ) //获取line中文字在整段文字中的Range

CFArrayRef CTLineGetGlyphRuns (CTLineRef line ) //获取line中包含所有run的数组

CFRange CTRunGetStringRange (CTRunRef run ) //获取run在整段文字中的Range

CFIndex CTLineGetStringIndexForPosition(

CTLineRef line,

CGPoint position ) //获取点击处position文字在整段文字中的index

CGFloat CTLineGetOffsetForStringIndex(

CTLineRef line,

CFIndex charIndex,

CGFloat* secondaryOffset ) //获取整段文字中charIndex位置的字符相对line的原点的x值

主要步骤:

1)计算并存储文字中保含的所有表情文字及其Range

2)替换表情文字为指定宽度的NSAttributedString

CTRunDelegateCallbacks callbacks;

callbacks.version = kCTRunDelegateVersion1;

callbacks.getAscent = ascentCallback;

callbacks.getDescent = descentCallback;

callbacks.getWidth = widthCallback;

callbacks.dealloc = deallocCallback;

CTRunDelegateRef runDelegate = CTRunDelegateCreate(&callbacks, NULL);

NSDictionary *attrDictionaryDelegate = [NSDictionary dictionaryWithObjectsAndKeys:

(id)runDelegate, (NSString*)kCTRunDelegateAttributeName,

[UIColor clearColor].CGColor,(NSString*)kCTForegroundColorAttributeName,

nil];

NSAttributedString *faceAttributedString = [[NSAttributedString alloc] initWithString:@"*" attributes:attrDictionaryDelegate];

[weiBoText replaceCharactersInRange:faceRange withAttributedString:faceAttributedString];

[faceAttributedString release];

3) 根据保存的表情文字的Range计算表情图片的Frame

textFrame 通过CTFrameGetLines 获取所有line的数组 lineArray

遍历lineArray中的line通过CTLineGetGlyphRuns获取line中包含run的数组 runArray

遍历runArray中的run 通过CTRunGetStringRange获取run的Range

判断表情文字的location是否在run的Range

如果在 通过CTLineGetOffsetForStringIndex获取x的值 y的值为line原点的值

4)Draw表情图片到计算获取到的Frame

(3)点击文字触发事件

主要步骤:

1) 根据touch事件获取点point

2) textFrame 通过CTFrameGetLineOrigins获取所有line的原点

3) 比较point和line原点的y值获取点击处于哪个line

4) line、point 通过CTLineGetStringIndexForPosition获取到点击字符在整段文字中的 index

5) NSAttributedString 通过index 用方法-(NSDictionary *)attributesAtIndex:(NSUInteger)location effectiveRange:(NSRangePointer)range 可以获取到点击到的NSAttributedString中存储的NSDictionary

6) 通过NSDictionary中存储的信息判断点击的哪种文字类型分别处理

11、iOS本地推送通知方法

可在应用后台执行时,本地弹出推送通知,也可以定时触发推送。

- (void)applicationDidEnterBackground:(UIApplication *)application

{

UIDevice* device = [UIDevice currentDevice];

BOOL backgroundSupported = NO;

if ([device respondsToSelector:@selector(isMultitaskingSupported)])

{

backgroundSupported = device.multitaskingSupported;

}

if (backgroundSupported && _bgTask==UIBackgroundTaskInvalid)

{

UIApplication *app = [UIApplication sharedApplication];

_bgTask = [app beginBackgroundTaskWithExpirationHandler:^{

}];

dispatch_async(dispatch_get_main_queue(), ^{

while (app.applicationState==UIApplicationStateBackground && _bgTask!=UIBackgroundTaskInvalid && [app backgroundTimeRemaining] > 10)

{

[NSThread sleepForTimeInterval:1];

NSLog(@"background task %d left left time %d.", _bgTask, (int)[app backgroundTimeRemaining]);

if ([app backgroundTimeRemaining] < 580)

{

UILocalNotification *localNotif = [[UILocalNotification alloc] init];

if (localNotif)

{

localNotif.alertBody = [NSString stringWithString:@"测试本地通知消息,后台提示功能。"];

localNotif.alertAction = NSLocalizedString(@"查看", nil);

localNotif.soundName = UILocalNotificationDefaultSoundName;

localNotif.applicationIconBadgeNumber = 1;

[application presentLocalNotificationNow:localNotif];

[localNotif release];

break;

}

}

}

NSLog(@"background task %d finished.", _bgTask);

[app endBackgroundTask:_bgTask];

_bgTask = UIBackgroundTaskInvalid;

});

}

}

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

推荐阅读更多精彩内容

  • 1、设置UILabel行间距 NSMutableAttributedString* attrString = [[...
    十年一品温如言1008阅读 1,647评论 0 3
  • 1、禁止手机睡眠[UIApplication sharedApplication].idleTimerDisabl...
    DingGa阅读 1,117评论 1 6
  • 1、设置UILabel行间距 NSMutableAttributedString* attrString = [[...
    FF_911阅读 1,368评论 0 3
  • 转自:http://www.code4app.com/blog-866962-1317.html1、设置UILab...
    MMOTE阅读 1,601评论 1 1
  • 我的面前放着一碗热气腾腾的面,常州银丝面。 来常州日久,却始终没有品尝过常州银丝面。不是因为路太远,就是因为我太懒...
    仁云阅读 889评论 3 1