IOS实用代码片段
来源:互联网 发布:51单片机型号 编辑:程序博客网 时间:2024/05/05 23:22
一、获取IOS屏幕尺寸大小
1.app尺寸,去掉状态栏CGRect r = [ UIScreen mainScreen ].applicationFrame;r=0,20,320,460
2.屏幕尺寸CGRect rx = [ UIScreen mainScreen ].bounds;r=0,0,320,480
3.状态栏尺寸CGRect rect; rect = [[UIApplication sharedApplication] statusBarFrame];
4.iphone中获取屏幕分辨率的方法CGRect rect = [[UIScreen mainScreen] bounds];CGSize size = rect.size;CGFloat width = size.width;CGFloat height = size.height;
二、Math中的round/ceil/floorf方法总结
转自:http://blog.csdn.net/wygzky/article/details/3292202
- public class RoundTest {
- public static void main(String[] args) {
- double[] values = {-2.3,-1.0,0.25,4,1.5};
- for(int i = 0; i < values.length; i++){
- System.out.println(Math.round(values[i]));
- System.out.println(Math.ceil(values[i]));
- System.out.println(Math.floor(values[i]));
- System.out.println("===========" + i + "============");
- }
- }
- }
CGGeometry
CGGeometry参考定义几何结构和功能,操作简单。数据结构中的一个点CGPoint代表在一个二维坐标系统。数据结构的位置和尺寸CGRect代表的一个长方形。数据结构的尺寸CGSize代表宽度和高度。1、创建一个几何原始数值
CGPoint CGPointMake(CGPoint A,CGPoint B)
返回一个指定坐标点
CGRect CGRectMake(CGFloat x,CGFloat y,CGFloat width,CGFloat height)
根据指定的坐标和大小创建一个矩形
CGSize CGSizeMake(CGFloat width,CGFloat height)
根据指定长宽创建一个CGSize
2、修改矩形
CGRectDivide
CGRect CGRectInset(CGRect rect,CGFloat dx,CGFloat dy)
返回一个比原矩形大或小的矩形,但是中心点是相同的
CGRect CGRectIntegral(CGRect A)
将矩形A的值转变成整数,得到一个最小的矩形,
CGRect CGRectIntersection:(CGRect A,CGRect B)
获取两个矩形相交处所的矩形,没有相交返回NULL,用CGRectIsNull来检测
CGRectOffset
CGRectStandardize
CGRectUnion
3、比较数值
bool CGPointEqualToPoint(CGPoint A,CGPoint B)
返回两个点是否相等
bool CGSizeEqualToSize(CGSize A,CGSize B)
CGSizeAB是否相等
bool CGRectEqualToRect(CGRect A,CGRect B)
矩形AB的位置大小是否相等
bool CGRectIntersectsRect(CGRect A,CGRect B)
矩形AB是否相交,可用来判断精灵是否离开了屏幕
4、检查
bool CGRectContainsPoint(CGRect A, CGPoint B)
检测矩形A是否包含指定的点B
bool CGRectContainsRect(CGRect A,CGRect B)
检测矩形A是否包含矩形B
5、获取最大值、中等职和最小值
CGFloat CGRectGetMinX(CGRect A)
获取矩形x坐标的最小值
CGFloat CGRectGetMinY(CGRect A)
获取矩形y坐标的最小值
CGFloat CGRectGetMidX(CGRect A)
获取矩形x坐标的中间值
CGFloat CGRectGetMidY(CGRect A)
获取矩形y坐标的中间值
CGFloat CGRectGetMaxX(CGRect A)
获取矩形x坐标的最大值
CGFloat CGRectGetMaxY(CGRect A)
获取矩形y坐标的最大值
6、获取高和宽
CGFloat CGRectGetHeight(CGRect A)
获取矩形A的高
CGFloat CGRectGetWidth(CGRect A)
获取矩形A的宽
7、检测矩形是否存在或是无穷大
bool CGRectIsEmpty(CGRect A)
矩形A是否长和宽都是0,或者是个NULL
bool CGRectIsNull(CGRect A)
矩形A是否为NULL
bool CGRectIsInfinite(CGRect A)
矩形A是否无穷大,没有边界
IOS7下设置UINavigationBar的颜色的方法已经改变(当然如果是用自定义图片的话请忽略~~~)
首先是区别iOS7和之前版本的方法如下:
//如果是iOS7以前的话if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1)
具体写法区别如下,其实就是多了个bar- -。。
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) { // Load resources for iOS 6.1 or earlier self.navigationController.navigationBar.tintColor = [UIColor brownColor]; } else { // Load resources for iOS 7 or later self.navigationController.navigationBar.barTintColor = [UIColor brownColor]; }
/ 把 图片 写入 沙盒 -(void)photoFile { //此处首先指定了图片存取路径(默认写到应用程序沙盒 中) NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); //并给文件起个文件名 NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"pin"]; BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath]; if (blHave) { NSLog(@"already have"); return ; } //此处的方法是将图片写到Documents文件中 如果写入成功会弹出一个警告框,提示图片保存成功 NSString *strPathOld = [[NSBundle mainBundle] pathForResource:@"pin" ofType:@"png"]; NSData *data = [NSData dataWithContentsOfFile:strPathOld]; BOOL result = [data writeToFile:uniquePath atomically:YES]; if (result) { NSLog(@"success"); }else { NSLog(@"no success"); } }// 删除沙盒里的文件-(void)deleteFile { NSFileManager* fileManager=[NSFileManager defaultManager]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); //文件名 NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"pin.png"]; BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath]; if (!blHave) { NSLog(@"no have"); return ; }else { NSLog(@" have"); BOOL blDele= [fileManager removeItemAtPath:uniquePath error:nil]; if (blDele) { NSLog(@"dele success"); }else { NSLog(@"dele fail"); } }}// 图片UIImage *img = [UIImage imageNamed:@"1.png"];NSData* data = UIImagePNGRepresentation(img);//向沙盒里 写入文件夹,并向文件夹里 写入东西 NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *folder = [document stringByAppendingPathComponent:@"folder"]; NSString *filePath = [folder stringByAppendingPathComponent:@"test.png"]; if (![fileManager fileExistsAtPath:folder]) { BOOL blCreateFolder= [fileManager createDirectoryAtPath:folder withIntermediateDirectories:NO attributes:nil error:NULL]; if (blCreateFolder) { NSLog(@" folder success"); }else { NSLog(@" folder fial"); } }else { NSLog(@" 沙盒文件已经存在"); } if (![fileManager fileExistsAtPath:filePath]) { NSString *strPathOld = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"png"]; NSData *data = [NSData dataWithContentsOfFile:strPathOld]; BOOL result = [data writeToFile:filePath atomically:YES]; if (result) { NSLog(@"success"); }else { NSLog(@"no success"); } }//得到沙盒文件夹 下的所有文件NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *document=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *folder =[document stringByAppendingPathComponent:@"folder"]; NSArray *fileList ; fileList =[fileManager contentsOfDirectoryAtPath:folder error:NULL]; for (NSString *file in fileList) { NSLog(@"file=%@",file); NSString *path =[folder stringByAppendingPathComponent:file]; NSLog(@"得到的路径=%@",path); }
六、iOS 判断邮箱,手机的方法
/*邮箱验证 MODIFIED BY HELENSONG*/-(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];}/*手机号码验证 MODIFIED BY HELENSONG*/-(BOOL) isValidateMobile:(NSString *)mobile{ //手机号以13, 15,18开头,八个 \d 数字字符 NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$"; NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];// NSLog(@"phoneTest is %@",phoneTest); return [phoneTest evaluateWithObject:mobile];}/*车牌号验证 MODIFIED BY HELENSONG*/ BOOL validateCarNo(NSString* carNo) { NSString *carRegex = @"^[A-Za-z]{1}[A-Za-z_0-9]{5}$"; NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex]; NSLog(@"carTest is %@",carTest); return [carTest evaluateWithObject:carNo]; }
七、xcode6 iOS sdk8.1隐藏系统状态栏
有两种方法
1、首先来看看,把后面的系统的状态栏给隐藏,代码如下(添加在播放的view上面):
- - (UIStatusBarStyle)preferredStatusBarStyle
- {
- return UIStatusBarStyleDefault;
- //UIStatusBarStyleDefault = 0 黑色文字,浅色背景时使用
- //UIStatusBarStyleLightContent = 1 白色文字,深色背景时使用
- }
- - (BOOL)prefersStatusBarHidden
- {
- return YES; // 返回NO表示要显示,返回YES将hiden
- }
这样的效果就显而易见了:
白条代替了系统状态栏
2、不写代码,通过修改.plist文件的方式隐藏
找到项目中的.plist(对应1所示)-------------------找到2的加号-----------------------选择3的Viewcontroller-based status bar appearance-------------------设置这个项的Boolean的值(NO表示不显示系统的状态栏)
效果其实也是一样的:
不过还是建议使用第一种方式
'-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "XXXView" nib but the view outlet was not set.'
查书才知道,没有做nib文件到xxxViewControler程序的关联,特此记录下来:
1, 打开nib文件
2, 点击"File's Owner", 按command+4,设置Class为xxxViewControler
3, 按Control+"Files's Owner", 里面有个默认的IBOutlet变量view, 看一下后面有没有做关联,如果没有就拉到下面的View和视图做个关联
<span style="font-size:18px;">UITableView所拥有的方法: - (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation NS_AVAILABLE_IOS(3_0);代码参考: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *CellIdentifier = @"CellIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (!cell) { cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease]; } NSString *state = [[self.area objectAtIndex:indexPath.row] objectForKey:@"State"]; cell.textLabel.text = state; //判断要显示的行是否与当前的选中行是同一行 if ([self.currentSelectIndexPath isEqual:indexPath]) { cell.accessoryType = UITableViewCellAccessoryCheckmark; }else{ cell.accessoryType = UITableViewCellAccessoryNone; } return cell;}#pragma mark - Table view delegate- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ self.lastSelectIndexPath = self.currentSelectIndexPath; self.currentSelectIndexPath = indexPath; //判断是否是第一次选择 if (self.lastSelectIndexPath) { //刷新之前选中行 [tableView reloadRowsAtIndexPaths:@[self.lastSelectIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; } //刷新当前选中行 [tableView reloadRowsAtIndexPaths:@[self.currentSelectIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];}</span>
十、用Block封装ASIHttpRequest
<span style="font-size:14px;">接口部分://// LYHASIRequestBlock.h// ASIBlockTest//// Created by Charles Leo on 14-7-23.// Copyright (c) 2014年 Charles Leo. All rights reserved.// #import <Foundation/Foundation.h>#import "ASIHTTPRequest.h"#import "ASIFormDataRequest.h"typedef void (^RequestBlock) (void);@interface LYHASIRequestBlock : NSObject <ASIHTTPRequestDelegate>{ ASIHTTPRequest * getRequest; ASIFormDataRequest * postRequest; NSURL * url; RequestBlock finishBlock; RequestBlock failBlock; RequestBlock startBlock; NSString * requestType;} //接收到的数据@property (strong,nonatomic) NSData * receiveData;//请求完成的block- (void)didFinishBlock:(RequestBlock)block;//请求失败的block- (void)didFailedBlock:(RequestBlock)block;//请求开始的block- (void)didStartBlock:(RequestBlock)block;//取消请求- (void)cancelRequst;//get请求方法- (void)getRequest:(NSString *)getUrl;//post请求方法- (void)postRequest:(NSString *)postUrl andKeys:(NSArray *)keyArray andValues:(NSArray *)valueArray;@end 实现部分://// LYHASIRequestBlock.m// ASIBlockTest//// Created by Charles Leo on 14-7-23.// Copyright (c) 2014年 Charles Leo. All rights reserved.// #import "LYHASIRequestBlock.h" @implementation LYHASIRequestBlock - (void)getRequest:(NSString *)getUrl{ requestType = @"GET"; getRequest = [[ASIHTTPRequest alloc]initWithURL:[NSURL URLWithString:getUrl]]; getRequest.delegate = self; getRequest.timeOutSeconds = 15; [getRequest startAsynchronous];}#pragma mark -GET请求的代理方法//开始请求- (void)requestStarted:(ASIHTTPRequest *)request{ startBlock();}//请求完成- (void)requestFinished:(ASIHTTPRequest *)request{ self.receiveData = request.responseData; finishBlock();}//请求失败- (void)requestFailed:(ASIHTTPRequest *)request{ failBlock();}//post请求-(void)postRequest:(NSString *)postUrl andKeys:(NSArray *)keyArray andValues:(NSArray *)valueArray{ postRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:postUrl]]; postRequest.timeOutSeconds = 15; postRequest.delegate = self; for (int i = 0; i<keyArray.count; i++) { [postRequest setPostValue:[valueArray objectAtIndex:i] forKey:[keyArray objectAtIndex:i]]; } [postRequest setDidFinishSelector:@selector(didFinishPostRequest:)]; [postRequest setDidStartSelector:@selector(didStartPostRequest:)]; [postRequest setDidFailSelector:@selector(didFailPostRequest:)]; [postRequest startAsynchronous];} #pragma mark - POST请求的代理方法//请求开始- (void)didStartPostRequest:(ASIFormDataRequest *)request{ startBlock();}//请求完成- (void)didFinishPostRequest:(ASIFormDataRequest *)request{ finishBlock();}//请求失败- (void)didFailPostRequest:(ASIFormDataRequest *)request{ failBlock();} //设置Blocks//设置开始块- (void)didStartBlock:(RequestBlock)block{ [startBlock release]; startBlock = [block copy];}//设置完成块-(void)didFinishBlock:(RequestBlock)block{ [finishBlock release]; finishBlock = [block copy];}//设置失败块-(void)didFailedBlock:(RequestBlock)block{ [failBlock release]; failBlock = [block copy];}//取消请求- (void)cancelRequst{ if ([requestType isEqualToString:@"GET"]) { [getRequest cancel]; } else if([requestType isEqualToString:@"POST"]) { [postRequest cancel]; }} -(void)dealloc{ [getRequest release]; [postRequest release]; [startBlock release]; [finishBlock release]; [failBlock release]; [super dealloc];}@end</span>
转自:http://leopard168.blog.163.com/blog/static/168471844201410411215586/
- IOS实用代码片段
- iOS实用代码片段
- IOS实用代码片段 2
- iOS实用的代码片段
- 实用代码片段
- Android实用代码片段
- 实用的代码片段
- android实用代码片段
- android实用代码片段
- Andrioid 实用代码片段
- Android实用代码片段
- android 实用代码片段
- Android实用代码片段
- 实用代码片段
- Android 实用代码片段
- 实用代码片段--Javascript
- [代码片段] Android实用代码片段整合
- 实用jquery代码片段集合
- 李红霞作业第二章52页22题
- 墙上时间
- 修改一下前几天的贪吃蛇代码。。。
- awk模式
- 36kr2.0上线了-正中要害
- IOS实用代码片段
- 第六周上机实践项目6-复数模板类(3、友元的实现)
- c++函数返回引用
- linux 命令之wc
- err.number与err.Description
- Maven 打包时排除不想打包的文件&跳过测试
- 认识DOS
- 嵌入式系统多媒体框架分析
- VC连接数据库输出乱码的解决方案