开发常用代码整理(1)✨
版权声明:本文为博主原创文章,未经博主允许不得转载。
![](https://img.haomeiwen.com/i838345/69cf6cf5e50c2500.jpg)
iPhone Size:
手机型号 | 屏幕尺寸 |
---|---|
iPhone 4 4s | 320 * 480 |
iPhone 5 5s | 320 * 568 |
iPhone 6 6s | 375 * 667 |
iphone 6 plus 6s plus | 414 * 736 |
1.判断邮箱格式是否正确的代码:
//利用正则表达式验证
-(BOOL)isValidateEmail:(NSString *)email
{
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];
return [emailTest evaluateWithObject:email];
}
2.图片压缩
用法:UIImage *yourImage= [self imageWithImageSimple:image scaledToSize:CGSizeMake(210.0, 210.0)];
//压缩图片
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
// 创建一个图形文本
UIGraphicsBeginImageContext(newSize);
//画出新文本的尺寸
// new size
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
//从文本上得到一个新的图片
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
// 结束编辑文本
UIGraphicsEndImageContext();
// Return the new image.
return newImage;
}
3.亲测可用的图片上传代码
//按钮响应事件
- (IBAction)uploadButton:(id)sender {
UIImage *image = [UIImage imageNamed:@"1.jpg"]; //图片名
NSData *imageData = UIImageJPEGRepresentation(image,0.5);//压缩比例
NSLog(@"字节数:%i",[imageData length]);
// post url
NSString *urlString = @"http://192.168.1.113:8090/text/UploadServlet";
//服务器地址
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
//
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data;boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
//
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition:form-data; name=\"userfile\"; filename=\"2.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; //上传上去的图片名字
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
// NSLog(@"1-body:%@",body);
NSLog(@"2-request:%@",request);
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"3-测试输出:%@",returnString);
4.对图库的操作
//选择相册:
UIImagePickerControllerSourceTypesourceType=UIImagePickerControllerSourceTypeCamera;
if (![UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
}
UIImagePickerController * picker = [[UIImagePickerControlleralloc]init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = sourceType;
[self presentModalViewController:picker animated:YES];
//选择完毕:
-(void)imagePickerController:(UIImagePickerController*)pickerdidFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissModalViewControllerAnimated:YES];
UIImage * image=[info objectForKey:UIImagePickerControllerEditedImage];
[self performSelector:@selector(selectPic:) withObject:imageafterDelay:0.1];
}
-(void)selectPic:(UIImage*)image
{
NSLog(@"image%@",image);
imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
[self.viewaddSubview:imageView];
[self performSelectorInBackground:@selector(detect:) withObject:nil];
}
//detect为自己定义的方法,编辑选取照片后要实现的效果
//取消选择:
-(void)imagePickerControllerDIdCancel:(UIImagePickerController*)picker
{
[picker dismissModalViewControllerAnimated:YES];
}
5.创建一个UIBarButtonItem右边按钮
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"右边" style:UIBarButtonItemStyleDone target:self action:@selector(clickRightButton)];
[self.navigationItem setRightBarButtonItem:rightButton];
6.设置navigationBar隐藏
self.navigationController.navigationBarHidden = YES;//```
7.iOS开发之UIlabel多行文字自动换行 (自动折行)
UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(10, 100, 300, 180)];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, 300, 150)];
label.text = @"Hello world! Hello world!Hello world! Hello world! Hello world! Hello world! Hello world! Hello world!Hello world! Hello world! Hello world! Hello world! Hello world! Helloworld!";
//自动折行设置
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;```
8.代码生成button
CGRect frame = CGRectMake(0, 400, 72.0, 37.0);
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = frame;
[button setTitle:@"新添加的按钮" forState: UIControlStateNormal];
button.backgroundColor = [UIColor clearColor];
button.tag = 2000;
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];```
9.让某个控件在View的中心位置显示:
(某个控件,比如label,View)label.center = self.view.center;```
10.好看的文字处理
以tableView中cell的textLabel为例子:
cell.backgroundColor = [UIColorscrollViewTexturedBackgroundColor];
//设置文字的字体
cell.textLabel.font = [UIFont fontWithName:@"AmericanTypewriter" size:100.0f];
//设置文字的颜色
cell.textLabel.textColor = [UIColor orangeColor];
//设置文字的背景颜色
cell.textLabel.shadowColor = [UIColor whiteColor];
//设置文字的显示位置
cell.textLabel.textAlignment = UITextAlignmentCenter;```
11. 隐藏Status Bar
读者可能知道一个简易的方法,那就是在程序的viewDidLoad中加入
[[UIApplication sharedApplication]setStatusBarHidden:YES animated:NO];```
- 更改AlertView背景
UIAlertView *theAlert = [[[UIAlertViewalloc] initWithTitle:@"Atention"
message: @"I'm a Chinese!"
delegate:nil
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Okay",nil] autorelease];
[theAlert show];
UIImage *theImage = [UIImageimageNamed:@"loveChina.png"];
theImage = [theImage stretchableImageWithLeftCapWidth:0topCapHeight:0];
CGSize theSize = [theAlert frame].size;
UIGraphicsBeginImageContext(theSize);
[theImage drawInRect:CGRectMake(5, 5, theSize.width-10, theSize.height-20)];//这个地方的大小要自己调整,以适应alertview的背景颜色的大小。
theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
theAlert.layer.contents = (id)[theImage CGImage];```
13.键盘透明
textField.keyboardAppearance = UIKeyboardAppearanceAlert;```
14.状态栏的网络活动风火轮是否旋转
[UIApplication sharedApplication].networkActivityIndicatorVisible,默认值是NO。```
15.截取屏幕图片
//创建一个基于位图的图形上下文并指定大小为CGSizeMake(200,400)
UIGraphicsBeginImageContext(CGSizeMake(200,400));
//renderInContext 呈现接受者及其子范围到指定的上下文
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
//返回一个基于当前图形上下文的图片
UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();
//移除栈顶的基于当前位图的图形上下文
UIGraphicsEndImageContext();
//以png格式返回指定图片的数据
imageData = UIImagePNGRepresentation(aImage);```
16.更改cell选中的背景
UIView *myview = [[UIView alloc] init];
myview.frame = CGRectMake(0, 0, 320, 47);
myview.backgroundColor = [UIColorcolorWithPatternImage:[UIImage imageNamed:@"0006.png"]];
cell.selectedBackgroundView = my view;```
17.能让图片适应框的大小(没有确认)
NSString*imagePath = [[NSBundle mainBundle] pathForResource:@"XcodeCrash"ofType:@"png"];
UIImage *image = [[UIImage alloc]initWithContentsOfFile:imagePath];
UIImage *newImage= [image transformWidth:80.f height:240.f];
UIImageView *imageView = [[UIImageView alloc]initWithImage:newImage];
[newImagerelease];
[image release];
[self.view addSubview:imageView];```
18.如果只是想把当前页面的状态栏隐藏的话,直接用下面的代码就可以了
[[UIApplication sharedApplication] setStatusBarHidden:TRUE];```
19. 如果是想把整个应用程序的状态栏都隐藏掉,操作如下:
在info.plist上添加一项:Status bar is initially hidden,value为YES;
完后在MainAppDelegate.mm的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法里面加上如下一句就可以了:
[[UIApplication sharedApplication]setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];```
20.增强版NSLog
//A better version of 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)
21.给navigation Bar 设置 title 颜色
UIColor *whiteColor = [UIColor whiteColor];NSDictionary *dic = [NSDictionary dictionaryWithObject:whiteColor forKey:NSForegroundColorAttributeName];
[self.navigationController.navigationBar setTitleTextAttributes:dic];
22.如何把一个CGPoint存入数组里
CGPoint itemSprite1position = CGPointMake(100, 200);NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:NSStringFromCGPoint(itemSprite1position),nil];
// 从数组中取值的过程是这样的
CGPoint point = CGPointFromString([array objectAtIndex:0]);NSLog(@"point is %@.", NSStringFromCGPoint(point));
//可以用NSValue进行基础数据的保存,用这个方法更加清晰明确。
CGPoint itemSprite1position = CGPointMake(100, 200);
NSValue *originValue = [NSValue valueWithCGPoint:itemSprite1position];
NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:originValue, nil];
// 从数组中取值的过程是这样的:
NSValue *currentValue = [array objectAtIndex:0];
CGPoint point = [currentValue CGPointValue];
NSLog(@"point is %@.", NSStringFromCGPoint(point));
现在Xcode7后OC支持泛型了,可以用NSMutableArray<NSString *> *array来保存。
23.UIColor 获取 RGB 值
UIColor *color = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
const CGFloat *components = CGColorGetComponents(color.CGColor);
NSLog(@"Red: %f", components[0]);
NSLog(@"Green: %f", components[1]);
NSLog(@"Blue: %f", components[2]);
NSLog(@"Alpha: %f", components[3]);
24.修改textField的placeholder的字体颜色、大小
self.textField.placeholder = @"username is in here!";
[self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[self.textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
25.两点之间的距离
static inline CGFloat CGPointDistanceBetweenTwoPoints(CGPoint point1, CGPoint point2)
{
CGFloat dx = point2.x - point1.x; CGFloat dy = point2.y - point1.y; return sqrt(dxdx + dydy);
}
26.iOS开发-关闭/收起键盘方法总结
//1、点击Return按扭时收起键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField { return [textField resignFirstResponder]; }
//2、点击背景View收起键盘(你的View必须是继承于UIControl)
[self.view endEditing:YES];
//3、你可以在任何地方加上这句话,可以用来统一收起键盘
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
27.在使用 ImagesQA.xcassets 时需要注意
将图片直接拖入image到ImagesQA.xcassets中时,图片的名字会保留。这个时候如果图片的名字过长,那么这个名字会存入到ImagesQA.xcassets中,名字过长会引起SourceTree判断异常。
28.UIPickerView 判断开始选择到选择结束
开始选择的,需要在继承UiPickerView,创建一个子类,在子类中重载
- (UIView)hitTest:(CGPoint)point withEvent:(UIEvent)event
当[super hitTest:point withEvent:event]
返回不是nil的时候,说明是点击中UIPickerView中了。结束选择的, 实现UIPickerView的delegate方法
- (void)pickerView:(UIPickerView*)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
当调用这个方法的时候,说明选择已经结束了。
29.iOS模拟器 键盘事件
当iOS模拟器 选择了Keybaord->Connect Hardware keyboard 后,不弹出键盘。
//当代码中添加了
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide) name:UIKeyboardWillHideNotification object:nil];
进行键盘事件的获取。那么在此情景下将不会调用- (void)keyboardWillHide
.因为没有键盘的隐藏和显示。
30.在ios7上使用size classes后上面下面黑色
使用了size classes后,在ios7的模拟器上出现了上面和下面部分的黑色
可以在General->App Icons and Launch Images->Launch Images Source中设置Images.xcassets来解决。
![](https://img.haomeiwen.com/i1693553/94db70588023db1e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
31.线程中更新 UILabel的text
[self.label1 performSelectorOnMainThread:@selector(setText:) withObject:textDisplay waitUntilDone:YES];
label1 为UILabel,当在子线程中,需要进行text的更新的时候,可以使用这个方法来更新。其他的UIView 也都是一样的。
32.使用UIScrollViewKeyboardDismissMode实现了Message app的行为
像Messages app一样在滚动的时候可以让键盘消失是一种非常好的体验。然而,将这种行为整合到你的app很难。幸运的是,苹果给UIScrollView添加了一个很好用的属性keyboardDismissMode,这样可以方便很多。
现在仅仅只需要在Storyboard中改变一个简单的属性,或者增加一行代码,你的app可以和办到和Messages app一样的事情了。
这个属性使用了新的UIScrollViewKeyboardDismissMode enum枚举类型。这个enum枚举类型可能的值如下:
typedef NS_ENUM(NSInteger, UIScrollViewKeyboardDismissMode)
{
UIScrollViewKeyboardDismissModeNone,
UIScrollViewKeyboardDismissModeOnDrag, // dismisses the keyboard when a drag begins
UIScrollViewKeyboardDismissModeInteractive, // the keyboard follows the dragging touch off screen, and may be pulled upward again to cancel the dismiss
} NS_ENUM_AVAILABLE_IOS(7_0);
以下是让键盘可以在滚动的时候消失需要设置的属性:
![](https://img.haomeiwen.com/i1693553/6effe7793d3398d7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
33.报错 "_sqlite3_bind_blob", referenced from:
将 sqlite3.dylib加载到framework
34.ios7 statusbar 文字颜色
iOS7上,默认status bar字体颜色是黑色的,要修改为白色的需要在infoPlist里设置UIViewControllerBasedStatusBarAppearance为NO,然后在代码里添加:
[application setStatusBarStyle:UIStatusBarStyleLightContent];
35.获得当前硬盘空间
NSFileManager *fm = [NSFileManager defaultManager];
NSDictionary *fattributes = [fm attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
NSLog(@"容量%lldG",[[fattributes objectForKey:NSFileSystemSize] longLongValue]/1000000000);
NSLog(@"可用%lldG",[[fattributes objectForKey:NSFileSystemFreeSize] longLongValue]/1000000000);
36.给UIView 设置透明度,不影响其他sub views
UIView设置了alpha值,但其中的内容也跟着变透明。有没有解决办法?
设置background color的颜色中的透明度
比如:
[self.testView setBackgroundColor:[UIColor colorWithRed:0.0 green:1.0 blue:1.0 alpha:0.5]];
设置了color的alpha, 就可以实现背景色有透明度,当其他sub views不受影响给color 添加 alpha,或修改alpha的值。
// Returns a color in the same color space as the receiver with the specified alpha component.
- (UIColor *)colorWithAlphaComponent:(CGFloat)alpha;
// eg.
[view.backgroundColor colorWithAlphaComponent:0.5];
37.将color转为UIImage
//将color转为UIImage
- (UIImage *)createImageWithColor:(UIColor *)color
{
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect); UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
38.NSTimer 用法
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(tick:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
在NSRunLoop 中添加定时器.
38.Bundle identifier 应用标示符
Bundle identifier 是应用的标示符,表明应用和其他APP的区别。
39.NSDate 获取几年前的时间
// 获取到40年前的日期
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear:-40];
self.birthDate = [gregorian dateByAddingComponents:dateComponents toDate:[NSDate date] options:0];
40.iOS加载启动图的时候隐藏statusbar
只需需要在info.plist中加入Status bar is initially hidden 设置为YES就好!```
![](https://img.haomeiwen.com/i1693553/8add6a7f7105fdd8.jpg)
41.iOS 开发,工程中混合使用 ARC 和非ARC
Xcode 项目中我们可以使用 ARC 和非 ARC 的混合模式。
如果你的项目使用的非 ARC 模式,则为 ARC 模式的代码文件加入 -fobjc-arc 标签。
如果你的项目使用的是 ARC 模式,则为非 ARC 模式的代码文件加入 -fno-objc-arc 标签。
添加标签的方法:
打开:你的target -> Build Phases -> Compile Sources.
双击对应的 *.m 文件
在弹出窗口中输入上面提到的标签 -fobjc-arc / -fno-objc-arc
点击 done 保存
42.iOS7 中 boundingRectWithSize:options:attributes:context:计算文本尺寸的使用
之前使用了NSString类的sizeWithFont:constrainedToSize:lineBreakMode:方法,但是该方法已经被iOS7 Deprecated了,而iOS7新出了一个boudingRectWithSize:options:attributes:context方法来代替。而具体怎么使用呢,尤其那个attribute.
NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:13]};
CGSize size = [@"相关NSString" boundingRectWithSize:CGSizeMake(100, 0) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
43.NSDate使用 注意
NSDate 在保存数据,传输数据中,一般最好使用UTC时间。
在显示到界面给用户看的时候,需要转换为本地时间。
44.在UIViewController中property的一个UIViewController的Present问题
如果在一个UIViewController A中有一个property属性为UIViewController B,实例化后,将BVC.view 添加到主UIViewController A.view上,如果在viewB上进行
- (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^)(void))completion NS_AVAILABLE_IOS(5_0);
的操作将会出现,“ **Presenting view controllers on detached view controllers is discouraged **” 的问题。
以为BVC已经present到AVC中了,所以再一次进行会出现错误。
可以使用
[self.view.window.rootViewController presentViewController:imagePicker animated:YES completion:^{ NSLog(@"Finished"); }];
来解决。
45.UITableViewCell indentationLevel 使用
UITableViewCell 属性 NSInteger indentationLevel 的使用, 对cell设置 indentationLevel的值,可以将cell 分级别。
还有 CGFloat indentationWidth; 属性,设置缩进的宽度。
总缩进的宽度: **indentationLevel * indentationWidth**
46.ActivityViewController 使用AirDrop分享
使用AirDrop 进行分享:
NSArray *array = @[@"test1", @"test2"];UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:array applicationActivities:nil];[self presentViewController:activityVC animated:YES completion:^{ NSLog(@"Air"); }];
就可以弹出界面:
![](https://img.haomeiwen.com/i1693553/624c5c81448c00a4.png)
47.获取CGRect的height
获取CGRect的height, 除了self.createNewMessageTableView.frame.size.height
这样进行点语法获取。
还可以使用CGRectGetHeight(self.createNewMessageTableView.frame)
进行直接获取。
除了这个方法还有func CGRectGetWidth(rect: CGRect) -> CGFloat
等等简单地方法
func CGRectGetMinX(rect: CGRect) -> CGFloat
func CGRectGetMidX(rect: CGRect) -> CGFloat
func CGRectGetMaxX(rect: CGRect) -> CGFloat
func CGRectGetMinY(rect: CGRect) -> CGFloat
48.打印 %
NSString *printPercentStr = [NSString stringWithFormat:@"%%"];
49.在工程中查看是否使用 IDFA
allentekiMac-mini:JiKaTongGit lihuaxie$ grep -r advertisingIdentifier .
grep: ./ios/Framework/AMapSearchKit.framework/Resources: No such file or directory
Binary file ./ios/Framework/MAMapKit.framework/MAMapKit matches
Binary file ./ios/Framework/MAMapKit.framework/Versions/2.4.1.e00ba6a/MAMapKit matches
Binary file ./ios/Framework/MAMapKit.framework/Versions/Current/MAMapKit matches
Binary file ./ios/JiKaTong.xcodeproj/project.xcworkspace/xcuserdata/lihuaxie.xcuserdatad/UserInterfaceState.xcuserstate matches
allentekiMac-mini:JiKaTongGit lihuaxie$
打开终端,到工程目录中, 输入:
grep -r advertisingIdentifier .
可以看到那些文件中用到了IDFA,如果用到了就会被显示出来。
50.APP 屏蔽 触发事件
// Disable user interaction when download finishes[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
51.设置Status bar颜色
status bar的颜色设置:
如果没有navigation bar, 直接设置
// make status bar background color
self.view.backgroundColor = COLOR_APP_MAIN;
如果有navigation bar, 在navigation bar 添加一个view来设置颜色。
// status bar color
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, -20, ScreenWidth, 20)];
[view setBackgroundColor:COLOR_APP_MAIN];
[viewController.navigationController.navigationBar addSubview:view];```
52.NSDictionary 转 NSString
// Start
NSDictionary *parametersDic = [NSDictionary dictionaryWithObjectsAndKeys:self.providerStr, KEY_LOGIN_PROVIDER,token, KEY_TOKEN,response, KEY_RESPONSE,nil];
NSData *jsonData = parametersDic == nil ? nil : [NSJSONSerialization dataWithJSONObject:parametersDic options:0 error:nil];
NSString *requestBody = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
将dictionary 转化为 NSData, data 转化为 string .
53.iOS7 中UIButton setImage 没有起作用
如果在iOS7 中进行设置image 没有生效。
那么说明UIButton的 enable 属性没有生效是NO的。 需要设置enable 为YES。
54.User-Agent 判断设备UIWebView 会根据User-Agent 的值来判断需要显示哪个界面。如果需要设置为全局,那么直接在应用启动的时候加载。
-(void)appendUserAgent
{
NSString *oldAgent = [self.WebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString *newAgent = [oldAgent stringByAppendingString:@"iOS"];
NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:
newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dic];
}
@“iOS" 为添加的自定义。
55.UIPasteboard 屏蔽paste 选项
当UIpasteboard的string 设置为@“” 时,那么string会成为nil。 就不会出现paste的选项。 ```
56.class_addMethod 使用
**当 ARC 环境下**
class_addMethod([self class], @selector(resolveThisMethodDynamically), (IMP) myMethodIMP, "v@:");
使用的时候@selector 需要使用super的class,不然会报错。
**当MRC环境下**
class_addMethod([EmptyClass class], @selector(sayHello2), (IMP)sayHello, "v@:");
可以任意定义。但是系统会出现警告,忽略警告就可以。```
57.AFNetworking 传送 form-data
将JSON的数据,转化为NSData, 放入Request的body中。 发送到服务器就是form-data格式。```
58.非空判断注意
BOOL hasBccCode = YES;
if ( nil == bccCodeStr || [bccCodeStr isKindOfClass:[NSNull class]] || [bccCodeStr isEqualToString:@""])
{
hasBccCode = NO;
}
如果进行非空判断和类型判断时,**需要新进行类型判断,再进行非空判断,不然会crash**。```
59.iOS 8.4 UIAlertView 键盘显示问题
可以在调用UIAlertView 之前进行键盘是否已经隐藏的判断。
@property (nonatomic, assign) BOOL hasShowdKeyboard;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showKeyboard) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissKeyboard) name:UIKeyboardDidHideNotification object:nil];
-
(void)showKeyboard
{
self.hasShowdKeyboard = YES;
} -
(void)dismissKeyboard
{
self.hasShowdKeyboard = NO;
}
while ( self.hasShowdKeyboard )
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
UIAlertView* alerview = [[UIAlertView alloc] initWithTitle:@"" message:@"取消修改?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
[alerview show];
60.模拟器中文输入法设置
模拟器默认的配置种没有“小地球”,只能输入英文。加入中文方法如下:
选择Settings--->General-->Keyboard-->International KeyBoards-->Add New Keyboard-->Chinese Simplified(PinYin) 即我们一般用的简体中文拼音输入法,配置好后,再输入文字时,点击弹出键盘上的“小地球”就可以输入中文了。如果不行,可以长按“小地球”选择中文。
61.iPhone number pad
phone 的键盘类型:
1.number pad 只能输入数字,不能切换到其他输入:
![](https://img.haomeiwen.com/i1693553/f503c55fa712c976.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
2.phone pad 类型: 拨打电话的时候使用,可以输入数字和 + * # ```
![](https://img.haomeiwen.com/i1693553/d1d51e05f585cce0.png)
62.UIView 自带动画翻转界面
- (IBAction)changeImages:(id)sender
{
CGContextRef context = UIGraphicsGetCurrentContext();
[UIView beginAnimations:nil context:context];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:1.0];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:_parentView cache:YES];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:_parentView cache:YES];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:_parentView cache:YES];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:_parentView cache:YES];
NSInteger purple = [[_parentView subviews] indexOfObject:self.image1];
NSInteger maroon = [[_parentView subviews] indexOfObject:self.image2];
[_parentView exchangeSubviewAtIndex:purple withSubviewAtIndex:maroon];
[UIView setAnimationDelegate:self];
[UIView commitAnimations];
}
63.KVO 监听其他类的变量
[[HXSLocationManager sharedManager] addObserver:self forKeyPath:@"currentBoxEntry.boxCodeStr" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionOld context:nil];
在实现的类self中,进行[HXSLocationManager sharedManager]类中的变量@“currentBoxEntry.boxCodeStr” 监听。
64.ios9 crash animateWithDuration
在iOS9 中,如果进行animateWithDuration 时,view被release 那么会引起crash。
[UIView animateWithDuration:0.25f animations:^{
self.frame = selfFrame;
} completion:^(BOOL finished) {
if (finished)
{
[super removeFromSuperview];
}
}];
会crash。
[UIView animateWithDuration:0.25f delay:0 usingSpringWithDamping:1.0 initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveLinear animations:^{
self.frame = selfFrame;
} completion:^(BOOL finished) {
[super removeFromSuperview];
}];
不会Crash。
65.对NSString进行URL编码转换
iPTV项目中在删除影片时,URL中需传送用户名与影片ID两个参数。当用户名中带中文字符时,删除失败。
之前测试时,手机号绑定的用户名是英文或数字。换了手机号测试时才发现这个问题。
对于URL中有中文字符的情况,需对URL进行编码转换。
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
66.Xcode iOS加载图片只能用PNG
虽然在Xcode可以看到jpg的图片,但是在加载的时候会失败。错误为 Could not load the "ReversalImage1" image referenced from a nib in the bun
**必须使用PNG的图片。**
**如果需要使用JPG 需要添加后缀**
[UIImage imageNamed:@"myImage.jpg"];
67.保存全屏为image
CGSize imageSize = [[UIScreen mainScreen] bounds].size;
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
for (UIWindow * window in [[UIApplication sharedApplication] windows])
{
if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen])
{
CGContextSaveGState(context);
CGContextTranslateCTM(context, [window center].x, [window center].y);
CGContextConcatCTM(context, [window transform]);
CGContextTranslateCTM(context, -[window bounds].size.width*[[window layer] anchorPoint].x, -[window bounds].size.height*[[window layer] anchorPoint].y);
[[window layer] renderInContext:context];
CGContextRestoreGState(context);
}
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
68.判断定位状态 locationServicesEnabled
这个[CLLocationManager locationServicesEnabled]检测的是整个iOS系统的位置服务开关,无法检测当前应用是否被关闭。
通过:
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status)
{
[self locationManager:self.locationManager didUpdateLocations:nil];
}
else
{
// the user has closed this function
[self.locationManager startUpdatingLocation];
}
**CLAuthorizationStatus**来判断是否可以访问GPS
69.微信分享的时候注意大小
text 的大小必须 大于0 小于 10k
image 必须 小于 64k
url 必须 大于 0k```
70.图片缓存的清空
一般使用SDWebImage 进行图片的显示和缓存,一般缓存的内容比较多了就需要进行清空缓存
清除SDWebImage的内存和硬盘时,可以同时清除session 和 cookie的缓存。
// 清理内存
[[SDImageCache sharedImageCache] clearMemory];
// 清理webview 缓存
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [storage cookies])
{
[storage deleteCookie:cookie];
}
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config.URLCache removeAllCachedResponses];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
// 清理硬盘
[[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
[self.tableView reloadData];
}];
71.TableView Header View 跟随Tableview 滚动
当tableview的类型为 plain的时候,header View 就会停留在最上面。
当类型为 group的时候,header view 就会跟随tableview 一起滚动了。
72.TabBar的title 设置
在xib 或 storyboard 中可以进行tabBar的设置:
![](https://img.haomeiwen.com/i1693553/a4093ab06ce9a3a6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
其中badge 是自带的在图标上添加一个角标。
- self.navigationItem.title 设置navigation的title 需要用这个进行设置。
- self.title 在tab bar的主VC 中,进行设置self.title 会导致navigation 的title 和 tab bar的title一起被修改。
73.UITabBar,移除顶部的阴影
添加这两行代码:
[[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
[[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];
顶部的阴影是在UIWindow上的,所以不能简单的设置就去除。```
74.当一行中,多个UIKit 都是动态的宽度设置:```
![](https://img.haomeiwen.com/i1693553/8741beefc325157f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
设置horizontal的值,表示出现内容很长的时候,优先压缩这个UIKit。```
75.JSON的“<null>” 转换为nil
//使用AFNetworking 时, 使用
AFJSONResponseSerializer *response = [[AFJSONResponseSerializer alloc] init];
response.removesKeysWithNullValues = YES;
_sharedClient.responseSerializer = response;
这个参数 removesKeysWithNullValues 可以将null的值删除,那么就Value为nil了
76.iOS 随机颜色
view.backgroundColor = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1];```
77.获取时间戳
-(NSString *)created_at{
// Mon May 09 15:21:58 +0800 2016
//获取微博发送时间
//把获得的字符串时间 转成 时间戳
//EEE(星期) MMM(月份)dd(天) HH小时 mm分钟 ss秒 Z时区 yyyy年
NSDateFormatter *format = [[NSDateFormatter alloc]init];
format.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
//设置地区
format.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
//微博发送时间
NSDate *weiboDate = [format dateFromString:<"要展示的字符串">];
//获取当前时间
NSDate *nowDate = [NSDate new];
long nowTime = [nowDate timeIntervalSince1970];
long weiboTime = [weiboDate timeIntervalSince1970];
//微博时间和当前时间的时间差
long time = nowTime-weiboTime;
if (time<60) {//一分钟内 显示刚刚
return @"刚刚";
}else if (time>60&&time<=3600){
return [NSString stringWithFormat:@"%d分钟前",(int)time/60];
}else if (time>3600&&time<3600*24){
return [NSString stringWithFormat:@"%d小时前",(int)time/3600];
}else{//直接显示日期
format.dateFormat = @"MM月dd日";
return [format stringFromDate:weiboDate];
}
}
```swift
78.NSString的一些特殊情况
//__autoreleasing 对象设置为这样,要等到离自己最近的释放池销毁时才release
//__unsafe__unretained不安全不释放,为了兼容过去而存在,跟__weak很像,但是这个对象被销毁后还在,不像__weak那样设置为nil
//__weak 一创建完,要是没有引用,马上释放,将对象置nil
//
__weak NSMutableString *str = [NSMutableString stringWithFormat:@"%@",@"xiaobai"];
//__weak 的话但是是alloc的对象,要交给autorelease管理
//arc下,不要release 和 autorelease因为
79.设置UITabBarItem背景图片
if(iOS7)
{
item = [iteminitWithTitle:title[i]image:[unSelectImageimageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]selectedImage:[selectImageimageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
}
else
{
itemsetFinishedSelectedImage:selectImagewithFinishedUnselectedImage:unSelectImage];
item.title= title[i];
}
80.app跳转到safari
NSURL* url = [NSURL URLWithString:urlStr];
[[UIApplication sharedApplication] openURL:url];
81.每个cell的高度,(使用autolayout可以实现自动算高)
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//让tableview自动根据cell中的子视图的约束,来计算自己的高度
return UITableViewAutomaticDimension;
}
82.解决编码问题
中文应用都要遇到一个很头疼的问题:文字编码,汉字的 GBK 和 国际通用的 UTF-8 的互相转化稍一不慎,就会满屏乱码。下面介绍 UTF-8 和 GBK 的 NSString 相互转化的方法!
从 GBK 转到 UTF-8:
用 NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000) ,然后就可以用initWithData:encoding来实现。
从 UTF-8 转到 GBK:
CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000),得到的enc却是kCFStringEncodingInvalidId。
没关系,试试 NSData *data=[nsstring dataUsingEncoding:-2147482063];
注意:必须使用kCFStringEncodingGB_18030_2000这个字符集,那个kCFStringEncodingGB_2312_80试了也不行。
下图为证~!😝
![](https://img.haomeiwen.com/i2296108/0cd904afe26f4c3c.png)
![](https://img.haomeiwen.com/i2296108/7f1522b168545ada.png)
![](https://img.haomeiwen.com/i2296108/d97fcf84ca119ee6.png)
83.电池条的颜色
//方式一:
//新的电池条 风格调整: 在需要变化电池条样式的vc中, 重写下方方法即可
//新的方式: 当前电池条的颜色 基于当前控制器的设置.
- (UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContent;//白
}
//方式二:
//旧的方式: 电池条的颜色与VC无关. 这要修改plist文件, 把View controller-based status bar appearance属性设置为NO
- (void)viewDidLoad {
[super viewDidLoad];
//设置整个应用程序中所有页面的电池条颜色
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}
//还需要再info.plist中设置
![](https://img.haomeiwen.com/i2296108/e222d99911257df0.png)
84.xcode统计代码量方法:
1.打开终端,用cd命令 定位到工程所在的目录,然后调用以下命名即可把每个源代码文件行数及总数统计出来:
find . "(" -name "*.m" -or -name "*.mm" -or -name "*.cpp" -or -name "*.h" -or -name "*.rss" ")" -print | xargs wc -l
85:iOS适配 之 关于info.plist 第三方登录 添加URL Schemes白名单
近期苹果公司iOS 9系统策略更新,限制了http协议的访问,此外应用需要在“Info.plist”中将要使用的URL Schemes列为白名单,才可正常检查其他应用是否安装。
受此影响,当你的应用在iOS 9中需要使用 QQ/QQ空间/支付宝/微信SDK 的相关能力(分享、收藏、支付、登录等)时,需要在“Info.plist”里增加如下代码:
<key>LSApplicationQueriesSchemes</key>
<array>
<!-- 微信 URL Scheme 白名单-->
<string>wechat</string>
<string>weixin</string>
<!-- 新浪微博 URL Scheme 白名单-->
<string>sinaweibohd</string>
<string>sinaweibo</string>
<string>sinaweibosso</string>
<string>weibosdk</string>
<string>weibosdk2.5</string>
<!-- QQ、Qzone URL Scheme 白名单-->
<string>mqqapi</string>
<string>mqq</string>
<string>mqqOpensdkSSoLogin</string>
<string>mqqconnect</string>
<string>mqqopensdkdataline</string>
<string>mqqopensdkgrouptribeshare</string>
<string>mqqopensdkfriend</string>
<string>mqqopensdkapi</string>
<string>mqqopensdkapiV2</string>
<string>mqqopensdkapiV3</string>
<string>mqzoneopensdk</string>
<string>wtloginmqq</string>
<string>wtloginmqq2</string>
<string>mqqwpa</string>
<string>mqzone</string>
<string>mqzonev2</string>
<string>mqzoneshare</string>
<string>wtloginqzone</string>
<string>mqzonewx</string>
<string>mqzoneopensdkapiV2</string>
<string>mqzoneopensdkapi19</string>
<string>mqzoneopensdkapi</string>
<string>mqzoneopensdk</string>
<!-- 支付宝 URL Scheme 白名单-->
<string>alipay</string>
<string>alipayshare</string>
</array>
具体操作步骤:
右键 info.plist /Open as/Source Code 将上面的代码粘贴上去即可!
86.最近经常看到有人在群里问关于导航条透明的,废话不多说,直接上代码:
在ViewDidLoad方法里加上这三行代码:
self.navigationController.navigationBar.translucent = YES;
[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
[self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
在viewWillDisappear方法里加上这三行代码:
self.navigationController.navigationBar.translucent = NO;
[self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
[self.navigationController.navigationBar setShadowImage:nil];
self.navigationController.navigationBar.translucent分别表示开启、关闭导航条透明度
self.navigationController.navigationBar setBackgroundImage分别表示给导航条背景设置成空图片和恢复默认
[self.navigationController.navigationBar setShadowImage给赋值空的UIImage对象的目的是为了去除导航条透明时下面的黑线,当然赋值nil也是恢复默认咯
在这里有一点需要说明,如果没有禁用导航控制器的右滑pop手势的话,在viewWillDisappear里写那代码可能会有问题哦
导航侧滑pop手势没有禁用的时候,右滑、在上一个界面快完全显示的时候,左滑回去,然后。。。自己去试试吧,哈哈
87.所有屏幕尺寸的宏定义:
#define IPHONE5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : 0)
#define IPHONE4 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : 0)
#define IPHONE6 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) : 0)
#define IPHONE6PLUS ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : 0)