iOS開發(fā)過(guò)程中途戒,各種小問(wèn)題诵次,小技巧。持續(xù)更新......
- 返回輸入鍵盤
<UITextFieldDelegate>
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
- CGRect
CGRectFromString(<#NSString *string#>)//有字符串恢復(fù)出矩形
CGRectInset(<#CGRect rect#>, <#CGFloat dx#>, <#CGFloat dy#>)//創(chuàng)建較小或者較大的矩形
CGRectIntersectsRect(<#CGRect rect1#>, <#CGRect rect2#>)//判斷兩巨星是否交叉,是否重疊
CGRectZero//高度和寬度為零的闷板,位于(0逗柴,0)的矩形常量
- 隱藏狀態(tài)欄
[UIApplication sharedApplication] setStatusBarHidden:<#(BOOL)#> withAnimation:<#(UIStatusBarAnimation)#>//隱藏狀態(tài)欄
- 自動(dòng)適應(yīng)父視圖大小
self.view.autoresizesSubviews = YES;
self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
- UITableView的一些方法
這里我自己做了個(gè)測(cè)試蛹头,縮進(jìn)級(jí)別設(shè)置為行號(hào),row越大,縮進(jìn)越多
<UITableViewDelegate>
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger row = indexPath.row;
return row;
}
- 把plist文件中的數(shù)據(jù)賦給數(shù)組
NSString *path = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"];
NSArray *array = [NSArray arrayWithContentsOfFile:path];
- 獲取觸摸的點(diǎn)
- (CGPoint)locationInView:(UIView *)view;
- (CGPoint)previousLocationInView:(UIView *)view;
- 獲取觸摸的屬性
@property(nonatomic,readonly) NSTimeInterval timestamp;
@property(nonatomic,readonly) UITouchPhase phase;
@property(nonatomic,readonly) NSUInteger tapCount;
- 從plist中獲取數(shù)據(jù)賦給字典
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"book" ofType:@"plist"];
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];
- NSUserDefaults注意事項(xiàng)
設(shè)置完了以后如果存儲(chǔ)的東西比較重要的話渣蜗,一定要同步一下
[[NSUserDefaults standardUserDefaults] synchronize];
- 獲取Documents目錄
NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
- 獲取tmp目錄
NSString *tmpPath = NSTemporaryDirectory();
- 利用Safari打開一個(gè)鏈接
NSURL *url = [NSURL URLWithString:@"http://baidu.com"];
[[UIApplication sharedApplication] openURL:url];
- 利用UIWebView顯示pdf文件屠尊,網(wǎng)頁(yè)等等
<UIWebViewDelegate>
UIWebView *webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
webView.delegate = self;
webView.scalesPageToFit = YES;
webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[webView setAllowsInlineMediaPlayback:YES];
[self.view addSubview:webView];
NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"book" ofType:@"pdf"];
NSURL *url = [NSURL fileURLWithPath:pdfPath];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:5];
[webView loadRequest:request];
- UIWebView和html的簡(jiǎn)單交互
myWebView = [[UIWebView alloc]initWithFrame:self.view.bounds];
[myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
NSError *error;
NSString *errorString = [NSString stringWithFormat:@"<html><center><font size=+5 color='red'>AnError Occurred;<br>%@</font></center></html>",error];
[myWebView loadHTMLString:errorString baseURL:nil];
//頁(yè)面跳轉(zhuǎn)了以后,停止載入
-(void)viewWillDisappear:(BOOL)animated {
if (myWebView.isLoading) {
[myWebView stopLoading];
}
myWebView.delegate = nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- 漢字轉(zhuǎn)碼
NSString *oriString = @"\u67aa\u738b";
NSString *escapedString = [oriString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
- 處理鍵盤通知
先注冊(cè)通知耕拷,然后實(shí)現(xiàn)具體當(dāng)鍵盤彈出來(lái)要做什么讼昆,鍵盤收起來(lái)要做什么
- (void)registerForKeyboardNotifications {
keyboardShown = NO;//標(biāo)記當(dāng)前鍵盤是沒有顯示的
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
}
//鍵盤顯示要做什么
- (void)keyboardWasShown:(NSNotification *)notification {
if (keyboardShown) {
return;
}
NSDictionary *info = [notification userInfo];
NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
CGRect viewFrame = scrollView.frame;
viewFrame.size.height = keyboardSize.height;
CGRect textFieldRect = activeField.frame;
[scrollView scrollRectToVisible:textFieldRect animated:YES];
keyboardShown = YES;
}
- (void)keyboardWasHidden:(NSNotification *)notification {
NSDictionary *info = [notification userInfo];
NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
CGRect viewFrame = scrollView.frame;
viewFrame.size.height += keyboardSize.height;
scrollView.frame = viewFrame;
keyboardShown = NO;
}
- 點(diǎn)擊鍵盤的next按鈕,在不同的textField之間換行
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if ([textField returnKeyType] != UIReturnKeyDone) {
NSInteger nextTag = [textField tag] + 1;
UIView *nextTextField = [self.tableView viewWithTag:nextTag];
[nextTextField becomeFirstResponder];
}else {
[textField resignFirstResponder];
}
return YES;
}
- 設(shè)置日期格式
dateFormatter = [[NSDateFormatter alloc]init];
dateFormatter.locale = [NSLocale currentLocale];
dateFormatter.calendar = [NSCalendar autoupdatingCurrentCalendar];
dateFormatter.timeZone = [NSTimeZone defaultTimeZone];
dateFormatter.dateStyle = NSDateFormatterShortStyle;
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
- 加載大量圖片的時(shí)候骚烧,可以使用
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"icon" ofType:@"png"];
UIImage *myImage = [UIImage imageWithContentsOfFile:imagePath];
- 有時(shí)候在iPhone游戲中浸赫,既要播放背景音樂(lè),同時(shí)又要播放比如槍的開火音效赃绊。
NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:@"xx" ofType:@"wav"];
NSURL *musicURL = [NSURL fileURLWithPath:musicFilePath];
AVAudioPlayer *musicPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:musicURL error:nil];
[musicPlayer prepareToPlay];
musicPlayer.volume = 1;
musicPlayer.numberOfLoops = -1;//-1表示一直循環(huán)
- 從通訊錄中讀取電話號(hào)碼既峡,去掉數(shù)字之間的-
NSString *originalString = @"(123)123123abc";
NSMutableString *strippedString = [NSMutableString stringWithCapacity:originalString.length];
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
}else {
scanner.scanLocation = [scanner scanLocation] + 1;
}
}
NSLog(@"%@",strippedString);
- 正則判斷:字符串只包含字母和數(shù)字
NSString *myString = @"Letter1234";
NSString *regex = @"[a-z][A-Z][0-9]";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
if ([predicate evaluateWithObject:myString]) {
//implement
}
- 使用NSURLConnection下載數(shù)據(jù)
1. 創(chuàng)建對(duì)象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
[NSURLConnection connectionWithRequest:request delegate:self];
2. NSURLConnection delegate 委托方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
}
3. 實(shí)現(xiàn)委托方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
self.receiveData.length = 0;//先清空數(shù)據(jù)
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.receiveData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//錯(cuò)誤處理
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSString *returnString = [[NSString alloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding];
firstTimeDownloaded = YES;
}
- 隱藏狀態(tài)欄
[UIApplication sharedApplication].statusBarHidden = YES;
- 調(diào)用電話,短信碧查,郵件
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto:apple@mac.com?Subject=hello"]];
sms://調(diào)用短信
tel://調(diào)用電話
itms://打開MobileStore.app
- 獲取版本信息
UIDevice *myDevice = [UIDevice currentDevice];
NSString *systemVersion = myDevice.systemVersion;
- NSNotificationCenter帶參數(shù)發(fā)送
MPMoviePlayerController *theMovie = [[MPMoviePlayerController alloc]initWithContentURL:[NSURL fileURLWithPath:moviePath]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMovieFinishedCallback:) name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie];
[theMovie play];
- (void)myMovieFinishedCallback:(NSNotification *)aNotification {
MPMoviePlayerController *theMovie = [aNotification object];
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie];
}
- 延遲一段時(shí)間執(zhí)行某個(gè)函數(shù)
// (1) 調(diào)用NSObject的方法
[self performSelector:@selector(run) withObject:self afterDelay:2.0];
// 2秒后再調(diào)用self的run方法
// (2) 使用GCD函數(shù)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 2秒后異步執(zhí)行這里的代碼...
});
- 用NSDateFormatter調(diào)整時(shí)間格式代碼
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
- UIView設(shè)置成圓角的方法以及剪切多余部分
mainView.layer.cornerRadius = 6;
mainView.layer.masksToBounds = YES;
- iPhone 更改鍵盤右下角按鍵的 type
SearchBar *mySearchBar = [[UISearchBar alloc]init];
mySearchBar.frame = CGRectMake(0, 0, self.view.bounds.size.width, 44);
mySearchBar.placeholder = @"placeholderString";
mySearchBar.delegate = self;
[self.view addSubview:mySearchBar];
UITextField *searchField = [[mySearchBar subviews] lastObject];
searchField.returnKeyType = UIReturnKeyDone;
- tableView左滑出多個(gè)按鈕
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
//刪除按鈕
UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"刪除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath){
[_dataArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
}];
//置頂按鈕
UITableViewRowAction *toTopRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"置頂" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath){
NSLog(@"置頂");
}];
toTopRowAction.backgroundColor = [UIColor orangeColor];
//其他按鈕
UITableViewRowAction *otherRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"其他" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath){
NSLog(@"其他");
}];
otherRowAction.backgroundColor = [UIColor lightGrayColor];
//返回按鈕數(shù)組
return @[deleteRowAction, toTopRowAction, otherRowAction];
}
- 給圖片增加模糊效果
//加模糊效果运敢,image是圖片,blur是模糊度
+ (UIImage *)blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur {
//模糊度,
if ((blur < 0.1f) || (blur > 2.0f)) {
blur = 0.1f;
}
//boxSize必須大于0
int boxSize = (int)(blur * 100);
boxSize -= (boxSize % 2) + 1;
NSLog(@"boxSize:%i",boxSize);
//圖像處理
CGImageRef img = image.CGImage;
//圖像緩存,輸入緩存忠售,輸出緩存
vImage_Buffer inBuffer, outBuffer;
vImage_Error error;
//像素緩存
void *pixelBuffer;
//數(shù)據(jù)源提供者传惠,Defines an opaque type that supplies Quartz with data.
CGDataProviderRef inProvider = CGImageGetDataProvider(img);
// provider’s data.
CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
//寬,高稻扬,字節(jié)/行卦方,data
inBuffer.width = CGImageGetWidth(img);
inBuffer.height = CGImageGetHeight(img);
inBuffer.rowBytes = CGImageGetBytesPerRow(img);
inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
//像數(shù)緩存,字節(jié)行*圖片高
pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
outBuffer.data = pixelBuffer;
outBuffer.width = CGImageGetWidth(img);
outBuffer.height = CGImageGetHeight(img);
outBuffer.rowBytes = CGImageGetBytesPerRow(img);
// 第三個(gè)中間的緩存區(qū),抗鋸齒的效果
void *pixelBuffer2 = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
vImage_Buffer outBuffer2;
outBuffer2.data = pixelBuffer2;
outBuffer2.width = CGImageGetWidth(img);
outBuffer2.height = CGImageGetHeight(img);
outBuffer2.rowBytes = CGImageGetBytesPerRow(img);
//Convolves a region of interest within an ARGB8888 source image by an implicit M x N kernel that has the effect of a box filter.
error = vImageBoxConvolve_ARGB8888(&inBuffer;, &outBuffer2;, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
error = vImageBoxConvolve_ARGB8888(&outBuffer2;, &inBuffer;, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
error = vImageBoxConvolve_ARGB8888(&inBuffer;, &outBuffer;, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
if (error) {
NSLog(@"error from convolution %ld", error);
}
// NSLog(@"字節(jié)組成部分:%zu",CGImageGetBitsPerComponent(img));
//顏色空間DeviceRGB
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
//用圖片創(chuàng)建上下文,CGImageGetBitsPerComponent(img),7,8
CGContextRef ctx = CGBitmapContextCreate(
outBuffer.data,
outBuffer.width,
outBuffer.height,
8,
outBuffer.rowBytes,
colorSpace,
CGImageGetBitmapInfo(image.CGImage));
//根據(jù)上下文泰佳,處理過(guò)的圖片盼砍,重新組件
CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
//clean up
CGContextRelease(ctx);
CGColorSpaceRelease(colorSpace);
free(pixelBuffer);
free(pixelBuffer2);
CFRelease(inBitmapData);
CGImageRelease(imageRef);
return returnImage;
}
- 網(wǎng)易新聞?lì)^部滾動(dòng)切換
- (void)titleButtonDidClick:(UIButton *)titleButton
{
self.mainScrollView.contentOffset = CGPointMake(kScreenWidth * titleButton.tag, 0);
[UIView animateWithDuration:0.5 animations:^{
if (self.titleScrollView.contentOffset.x >= 0) {
self.titleScrollView.contentOffset = CGPointMake(titleButton.x - 150, 0);
}
// 先改變contentOffset,若偏移則修正
if (self.titleScrollView.contentOffset.x <= 0) {
self.titleScrollView.contentOffset = CGPointZero;
}
if (self.titleScrollView.contentOffset.x >= 2 * 900 - kScreenWidth) {
self.titleScrollView.contentOffset = CGPointMake(2 * 900 - kScreenWidth, 0);
}
}];
}
- 七牛上傳圖片的簡(jiǎn)單封裝
#import "QiNiuTool.h"
#import "JKRAccountTool.h"
#import "JKRAccount.h"
#import "QiniuSDK.h"
#import "QiNiuUpLoadResult.h"
#import <UIKit/UIKit.h>
@implementation QiNiuTool
+ (void)uploadImages:(NSArray *)images complete:(void (^)(NSDictionary *))complete
{
QNUploadManager *qnm = [[QNUploadManager alloc] init];
NSDateFormatter *mattter = [[NSDateFormatter alloc]init];
[mattter setDateFormat:@"yyyyMMddHHmmss"];
NSString *Nowdate = [mattter stringFromDate:[NSDate date]];
QiNiuUpLoadResult *result = [[QiNiuUpLoadResult alloc] init];
__block int count = 0;
for (int i = 0; i < images.count; i++) {
UIImage *image = images[i];
NSData *uploadData = UIImageJPEGRepresentation(image, 1);
//這里對(duì)大圖片做了壓縮乐纸,不需要的話下面直接傳uploadData就好
NSData *cutdownData = nil;
if (uploadData.length < 9999) {
cutdownData = UIImageJPEGRepresentation(image, 1.0);
} else if (uploadData.length < 99999) {
cutdownData = UIImageJPEGRepresentation(image, 0.6);
} else {
cutdownData = UIImageJPEGRepresentation(image, 0.3);
}
//[JKRAccountTool getAccount].token:token
[qnm putData:cutdownData key:[NSString stringWithFormat:@"%@%d", Nowdate, i+1] token:[JKRAccountTool getAccount].token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
count++;
NSString *resultKey = [NSString stringWithFormat:@"%d",i];
result.keys[resultKey] = [resp objectForKey:@"key"];
if (count == images.count) {
complete(result.keys);
}
} option:nil];
}
}
@end
- 導(dǎo)航條漸隱漸現(xiàn)
[_tableView addObserver: self forKeyPath: @"contentOffset" options: NSKeyValueObservingOptionNew context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
CGFloat offset=_tableView.contentOffset.y;
NSLog(@"offset:%f",offset);//越來(lái)越大 想要實(shí)現(xiàn)效果:一開始全顯示衬廷,后來(lái)顏色變淺
CGFloat delta=1-offset/100.f;
delta=MIN(1,delta);
NSLog(@"%f",delta);
self.navigationController.navigationBar.alpha=MIN(1,delta);
}
- 圖片壓縮
用法:UIImage *yourImage= [self imageWithImageSimple:image scaledToSize:CGSizeMake(210.0, 210.0)];
//壓縮圖片
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
// Create a graphics image context
UIGraphicsBeginImageContext(newSize);
// Tell the old image to draw in this newcontext, with the desired
// new size
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
// Get the new image from the context
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
// End the context
UIGraphicsEndImageContext();
// Return the new image.
return newImage;
}
- 圖片裁剪,類似新浪微博小圖顯示效果
CGSize asize = CGSizeMake(300, 300);
UIImage *newimage;
UIImage *image = [UIImage imageNamed:@""];
if (nil == image) {
newimage = nil;
}
else{
CGSize oldsize = image.size;
CGRect rect;
if (asize.width/asize.height > oldsize.width/oldsize.height) {
rect.size.width = asize.width;
rect.size.height = asize.width*oldsize.height/oldsize.width;
rect.origin.x = 0;
rect.origin.y = (asize.height - rect.size.height)/2;
}
else{
rect.size.width = asize.height*oldsize.width/oldsize.height;
rect.size.height = asize.height;
rect.origin.x = (asize.width - rect.size.width)/2;
rect.origin.y = 0;
}
UIGraphicsBeginImageContext(asize);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClipToRect(context, CGRectMake(0, 0, asize.width, asize.height));
CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
[image drawInRect:rect];
newimage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
UIImageView * imgView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 100, 100)];
imgView.image = newimage;
[self.view addSubview:imgView];
- 把時(shí)間戳轉(zhuǎn)換為時(shí)間
+ (NSDate *)dateWithTimeIntervalInMilliSecondSince1970:(double)timeIntervalInMilliSecond {
NSDate *ret = nil;
double timeInterval = timeIntervalInMilliSecond;
// judge if the argument is in secconds(for former data structure).
if(timeIntervalInMilliSecond > 140000000000) {
timeInterval = timeIntervalInMilliSecond / 1000;
}
ret = [NSDate dateWithTimeIntervalSince1970:timeInterval];
return ret;
}
- 自定義cell中獲取不到cell實(shí)際大小的辦法
-(void)drawRect:(CGRect)rect {
// 重寫此方法汽绢,并在此方法中獲取
CGFloat width = self.frame.size.width;
}
- 長(zhǎng)按圖標(biāo)抖動(dòng)
-(void)longPress:(UILongPressGestureRecognizer*)longPress
{
if (longPress.state==UIGestureRecognizerStateBegan) {
CAKeyframeAnimation* anim=[CAKeyframeAnimation animation];
anim.keyPath=@"transform.rotation";
anim.values=@[@(angelToRandian(-7)),@(angelToRandian(7)),@(angelToRandian(-7))];
anim.repeatCount=MAXFLOAT;
anim.duration=0.2;
[self.imageView.layer addAnimation:anim forKey:nil];
self.btn.hidden=NO;
}
}
- 阿拉伯?dāng)?shù)字轉(zhuǎn)化為漢語(yǔ)數(shù)字
+(NSString *)translation:(NSString *)arebic
{ NSString *str = arebic;
NSArray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"];
NSArray *chinese_numerals = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"];
NSArray *digits = @[@"個(gè)",@"十",@"百",@"千",@"萬(wàn)",@"十",@"百",@"千",@"億",@"十",@"百",@"千",@"兆"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chinese_numerals forKeys:arabic_numerals];
NSMutableArray *sums = [NSMutableArray array];
for (int i = 0; i < str.length; i ++) {
NSString *substr = [str substringWithRange:NSMakeRange(i, 1)];
NSString *a = [dictionary objectForKey:substr];
NSString *b = digits[str.length -i-1];
NSString *sum = [a stringByAppendingString:b];
if ([a isEqualToString:chinese_numerals[9]])
{
if([b isEqualToString:digits[4]] || [b isEqualToString:digits[8]])
{
sum = b;
if ([[sums lastObject] isEqualToString:chinese_numerals[9]])
{
[sums removeLastObject];
}
}else
{
sum = chinese_numerals[9];
}
if ([[sums lastObject] isEqualToString:sum])
{
continue;
}
}
[sums addObject:sum];
}
NSString *sumStr = [sums componentsJoinedByString:@""];
NSString *chinese = [sumStr substringToIndex:sumStr.length-1];
NSString *str1 = [[NSString alloc] init];
NSString *str2 = [[NSString alloc] init];
//將億萬(wàn)替換成億
if([chinese rangeOfString:@"億萬(wàn)"].location !=NSNotFound)
{
str1 = [chinese stringByReplacingOccurrencesOfString:@"億萬(wàn)" withString:@"億"];
}
else{
str1 = chinese;
}
//如果開頭以一十開頭則替換成十
if ( [str1 hasPrefix:@"一十"]) {
str2 = [str1 stringByReplacingOccurrencesOfString:@"一十" withString:@"十"];
}
else{
str2 = str1;
}
NSLog(@"%@",str);
NSLog(@"%@",str2);
return str2;
}
- 兩種方法刪除NSUserDefaults所有記錄
//方法一
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
//方法二
- (void)resetDefaults {
NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
NSDictionary * dict = [defs dictionaryRepresentation];
for (id key in dict) {
[defs removeObjectForKey:key];
}
[defs synchronize];
}
- 截屏 全圖
- (UIImage *)imageFromView: (UIView *) theView
{
UIGraphicsBeginImageContext(theView.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[theView.layer renderInContext:context];
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
- 判斷是否用戶開啟了定位服務(wù)
if ([CLLocationManager locationServicesEnabled] &&
([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized
|| [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)) {
//定位功能可用吗跋,開始定位
_locationManger = [[CLLocationManager alloc] init];
locationManger.delegate = self;
[locationManger startUpdatingLocation];
}
else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
NSlog("定位功能不可用,提示用戶或忽略");
}
- 圖片旋轉(zhuǎn)
UIImage * image = [UIImage imageNamed:@"iphone.png"];
NSData * tempData;
if (UIImagePNGRepresentation(image)) {
tempData = UIImagePNGRepresentation(image);
NSLog(@"%@",tempData);
}
else{
tempData = UIImageJPEGRepresentation(image, 1);
}
CIImage * iImg = [CIImage imageWithData:tempData];
UIImage * tImg = [UIImage imageWithCIImage:iImg scale:1 orientation:UIImageOrientationRight];
NSLog(@"%@",UIImagePNGRepresentation(tImg));
UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 200, 200, 80)];
imageView.image = tImg;
[self.view addSubview:imageView];
- 去除UIImageView鋸齒
imageView.layer.shouldRasterize = YES;
- 判斷兩個(gè)日期之間的間隔
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
NSDate* toDate = [dateFormatter dateFromString:@"19700608142033"];
NSDate* startDate = [ [ NSDate alloc] init ];
NSCalendar* chineseClendar = [ [ NSCalendar alloc ] initWithCalendarIdentifier:NSGregorianCalendar ];
NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit;
NSDateComponents *cps = [ chineseClendar components:unitFlags fromDate:startDate toDate:toDate options:0];
NSInteger diffYear = [cps year];
NSInteger diffMon = [cps month];
NSInteger diffDay = [cps day];
NSInteger diffHour = [cps hour];
NSInteger diffMin = [cps minute];
NSInteger diffSec = [cps second];
NSLog(@" From Now to %@, diff: Years: %d Months: %d, Days; %d, Hours: %d, Mins:%d, sec:%d", [toDate description], diffYear, diffMon, diffDay, diffHour, diffMin,diffSec );
- 類似微信發(fā)送視頻的流程
//獲取視頻的本地url或者path宁昭,對(duì)視頻進(jìn)行獲取第一幀圖片跌宛,然后初始化消息的Model,設(shè)置封面
NSString *mediaType = [editingInfo objectForKey: UIImagePickerControllerMediaType];
NSString *videoPath;
NSURL *videoUrl;
if (CFStringCompare ((__bridge CFStringRef) mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo) {
videoUrl = (NSURL*)[editingInfo objectForKey:UIImagePickerControllerMediaURL];
videoPath = [videoUrl path];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoUrl options:nil];
NSParameterAssert(asset);
AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
assetImageGenerator.appliesPreferredTrackTransform = YES;
assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
CGImageRef thumbnailImageRef = NULL;
CFTimeInterval thumbnailImageTime = 0;
NSError *thumbnailImageGenerationError = nil;
thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&thumbnailImageGenerationError;];
if (!thumbnailImageRef)
NSLog(@"thumbnailImageGenerationError %@", thumbnailImageGenerationError);
UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;
XHMessage *videoMessage = [[XHMessage alloc] initWithVideoConverPhoto:thumbnailImage videoPath:videoPath videoUrl:nil sender:@"Jack" timestamp:[NSDate date]];
[weakSelf addMessage:videoMessage];
}
- 刷新某行cell的方法
//有時(shí)候只需要刷新某行的cell的數(shù)據(jù)积仗,完全沒必要調(diào)用[tableView reloadData]刷新整個(gè)列表的數(shù)據(jù)疆拘,調(diào)用以下方法即可。
NSIndexPath *indexPath_1=[NSIndexPath indexPathForRow:1 inSection:0];
NSArray *indexArray=[NSArray arrayWithObject:indexPath_1];
[myTableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
- 由身份證號(hào)碼返回性別
-(NSString *)sexStrFromIdentityCard:(NSString *)numberStr{
NSString *result = nil;
BOOL isAllNumber = YES;
if([numberStr length]<17)
return result;
//**截取第17為性別識(shí)別符
NSString *fontNumer = [numberStr substringWithRange:NSMakeRange(16, 1)];
//**檢測(cè)是否是數(shù)字;
const char *str = [fontNumer UTF8String];
const char *p = str;
while (*p!='\0') {
if(!(*p>='0'&&*p<='9'))
isAllNumber = NO;
p++;
}
if(!isAllNumber)
return result;
int sexNumber = [fontNumer integerValue];
if(sexNumber%2==1)
result = @"男";
///result = @"M";
else if (sexNumber%2==0)
result = @"女";
//result = @"F";
return result;
}
- 數(shù)組隨機(jī)重新排列
+ (NSArray *)getRandomWithPosition:(NSInteger)position positionContent:(id)positionContent array:(NSArray *)baseArray {
NSMutableArray *resultArray = [NSMutableArray arrayWithCapacity:baseArray.count];
NSMutableArray *tempBaseArray = [NSMutableArray arrayWithArray:baseArray];
while ([tempBaseArray count]) {
NSInteger range = [tempBaseArray count];
id string = [tempBaseArray objectAtIndex:arc4random()%range];
[resultArray addObject:string];
[tempBaseArray removeObject:string];
}
NSUInteger index = [resultArray indexOfObject:positionContent];
[resultArray exchangeObjectAtIndex:index withObjectAtIndex:position - 1];
return resultArray;
}
- 利用陀螺儀實(shí)現(xiàn)更真實(shí)的微信搖一搖動(dòng)畫
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//想搖你的手機(jī)嘛寂曹?就寫在這哎迄,然后回右,然后,沒有然后了
application.applicationSupportsShakeToEdit=YES;
}
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if(motion==UIEventSubtypeMotionShake) {
// 真實(shí)一點(diǎn)的搖動(dòng)動(dòng)畫
[self addAnimations];
// 播放聲音
AudioServicesPlaySystemSound (soundID);
}
}
- (void)addAnimations {
CABasicAnimation *translation = [CABasicAnimation animationWithKeyPath:@"transform"];
translation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
translation.toValue=[NSValue valueWithCATransform3D:CATransform3DMakeRotation(-M_PI_4, 0, 0, 100)];
translation.duration = 0.2;
translation.repeatCount = 2;
translation.autoreverses = YES;
[shake.layer addAnimation:translation forKey:@"translation"];
}
- GIF圖片解析
+ (NSMutableArray *)praseGIFDataToImageArray:(NSData *)data;
{
NSMutableArray *frames = [[NSMutableArray alloc] init];
CGImageSourceRef src = CGImageSourceCreateWithData((CFDataRef)data, NULL);
CGFloat animationTime = 0.f;
if (src) {
size_t l = CGImageSourceGetCount(src);
frames = [NSMutableArray arrayWithCapacity:l];
for (size_t i = 0; i < l; i++) {
CGImageRef img = CGImageSourceCreateImageAtIndex(src, i, NULL);
NSDictionary *properties = (NSDictionary *)CGImageSourceCopyPropertiesAtIndex(src, i, NULL);
NSDictionary *frameProperties = [properties objectForKey:(NSString *)kCGImagePropertyGIFDictionary];
NSNumber *delayTime = [frameProperties objectForKey:(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
animationTime += [delayTime floatValue];
if (img) {
[frames addObject:[UIImage imageWithCGImage:img]];
CGImageRelease(img);
}
}
CFRelease(src);
}
return frames;
}
- 在后臺(tái)播放音樂(lè)
//1. 在Info.plist中漱挚,添加"Required background modes"鍵翔烁,其值設(shè)置是“App plays audio"
//2. 在播放器播放音樂(lè)的代碼所在處,添加如下兩段代碼(當(dāng)然旨涝,前提是已經(jīng)添加了AVFoundation框架)
//添加后臺(tái)播放代碼:
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
//以及設(shè)置app支持接受遠(yuǎn)程控制事件代碼蹬屹。設(shè)置app支持接受遠(yuǎn)程控制事件,
//其實(shí)就是在dock中可以顯示應(yīng)用程序圖標(biāo),同時(shí)點(diǎn)擊該圖片時(shí),打開app慎王。
//或者鎖屏?xí)r,雙擊home鍵厦取,屏幕上方出現(xiàn)應(yīng)用程序播放控制按鈕。
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
//用下列代碼播放音樂(lè)鸟赫,測(cè)試后臺(tái)播放
// 創(chuàng)建播放器
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[url release];
[player prepareToPlay];
[player setVolume:1];
player.numberOfLoops = -1; //設(shè)置音樂(lè)播放次數(shù) -1為一直循環(huán)
[player play]; //播放
- 添加TextFile時(shí),看不到時(shí)記得設(shè)置boardStyle屬性
UITextField *textField = [[UITextField alloc] init];
textField.frame = CGRectMake(50, 40, 120, 40);
//設(shè)置boardStyle屬性
textField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textField];
- 設(shè)置tableView的組與組間的頭部高度和尾部高度,可減小組間的間距
self.tableView.sectionFooterHeight = 10;
self.tableView.sectionHeaderHeight = 10;
- 實(shí)現(xiàn)tableView組標(biāo)題不懸浮效果
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (scrollView == self.tableView)
{
CGFloat sectionHeaderHeight = 25; //sectionHeaderHeight
if (scrollView.contentOffset.y <= sectionHeaderHeight&&scrollView.contentOffset.y >= 0) {
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
} else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
}
}
}
- table隱藏多余的空cell
tableView.tableFooterView = [[UIView alloc] init];
有時(shí)候想自定義tableView的分區(qū)頭/尾,但是自定義分區(qū)頭/尾的代理方法不執(zhí)行,這時(shí)候要檢查一下是否實(shí)現(xiàn)了返回高度的代理方法以及返回多少分區(qū)的代理方法.如果以上方法返回值為零或者不實(shí)現(xiàn)程序?qū)⒉粫?huì)執(zhí)行自定義分區(qū)頭的方法.
如何快速的查看一段代碼的執(zhí)行時(shí)間蒜胖。
//有的時(shí)候程序執(zhí)行一段代碼的時(shí)候有卡頓現(xiàn)象,想知道到底是哪一行代碼出現(xiàn)的問(wèn)題,可以這么做:
#define TICK NSDate *startTime = [NSDate date]
#define TOCK NSLog(@"Time: %f", -[startTime timeIntervalSinceNow])
//在想要查看執(zhí)行時(shí)間的代碼的地方進(jìn)行這么處理
TICK
//這里是代碼...
TOCK
開發(fā)中如果用到在一個(gè)viewController中添加另一個(gè)viewController的view,這時(shí)候一定要注意把viewController設(shè)置全局變量,否則會(huì)出現(xiàn)一些稀奇古怪的問(wèn)題.
自定義了leftBarbuttonItem左滑返回手勢(shì)失效了怎么辦?
//解決方法就是在自定義的導(dǎo)航欄的viewDidLoad方法中添加如下代碼
__weak typeof (self) weakSelf = self;
//解決因?yàn)樽远x導(dǎo)航欄按鈕,滑動(dòng)返回失效的問(wèn)題
if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.interactivePopGestureRecognizer.delegate = weakSelf;
}
- 另外再教大家一個(gè)實(shí)用的方法,當(dāng)Push的多個(gè)界面的導(dǎo)航欄返回按鈕相同時(shí),可以在自定義的UINavigationController中重寫Push的方法,攔截Push操作,
并同時(shí)設(shè)置push后的TabBar隱藏(如果有需要的話),代碼如下:
/**
* 重寫這個(gè)方法目的:能夠攔截所有push進(jìn)來(lái)的控制器
*
* @param viewController 即將push進(jìn)來(lái)的控制器
*/
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if (self.viewControllers.count > 0) { // 這時(shí)push進(jìn)來(lái)的控制器viewController,不是第一個(gè)子控制器(不是根控制器)
/* 自動(dòng)顯示和隱藏tabbar */
viewController.hidesBottomBarWhenPushed = YES;
/* 設(shè)置導(dǎo)航欄上面的內(nèi)容 */
// 設(shè)置左邊的返回按鈕
viewController.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(back) image:@"home_nav_bar_back_icon" highImage:@"home_nav_bar_back_icon"];
}
[super pushViewController:viewController animated:animated];
}
- (void)back
{
// 因?yàn)閟elf本來(lái)就是一個(gè)導(dǎo)航控制器抛蚤,self.navigationController這里是nil的
[self popViewControllerAnimated:YES];
}
- ScrollView莫名其妙不能在viewController劃到頂怎么辦?
self.automaticallyAdjustsScrollViewInsets = NO;
- 怎么點(diǎn)擊self.view就讓鍵盤收起
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
- 想在代碼里改在xib里添加的layoutAttributes
//像拉Button一樣地拉你的約束寻狂,nslayoutattribute也是可以拉線的岁经。
如果不想拉線的話,可以在這個(gè)方法里修改
-(void)viewDidAppear:(BOOL)animated{
}
- 怎么把我的navigationbar弄成透明的而不是帶模糊的效果?
self.navigationBar setBackgroundImage:[UIImage new]
forBarMetrics:UIBarMetricsDefault];
self.navigationBar.shadowImage = [UIImage new];
self.navigationBar.translucent = YES;
- 怎么改變uitextfield placeholder的顏色和位置蛇券?
//繼承uitextfield缀壤,重寫這個(gè)方法:
- (void) drawPlaceholderInRect:(CGRect)rect {
[[UIColor blueColor] setFill];
[self.placeholder drawInRect:rect withFont:self.font lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment];
}
- iOS9 HTTP 不能正常使用的解決辦法
1.在Info.plist中添加NSAppTransportSecurity類型Dictionary。
2.在NSAppTransportSecurity下添加NSAllowsArbitraryLoads類型Boolean,值設(shè)為YES
以上是在開發(fā)中經(jīng)常用到的一些方法,以供自己查閱以及大家使用,歡迎大家補(bǔ)充.
持續(xù)更新中...
更新時(shí)間: 2016.6.2