前言:
以下内容是作者在实际开发中所总结的,主要列举了一些实用小技巧,也希望在实际开发中能够帮到你。
- 设置控件的圆角:
myView.layer.cornerRadius = 6;
myView.layer.masksToBounds = YES;
transform = CGAffineTransformRotate(manImageView.transform,M_PI/6.0);
manImageView.frame=CGRectMake(100,100, 120,100);
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
transform = CGAffineTransformScale(manImageView.transform,1.2,1.2);
transform=CGAffineTransformInvert(manImageView.transform);
- 设置控件的阴影:
myView.layer.shadowColor = [UIColor blackColor].CGColor;
myView.layer.shadowOffset = CGSizeMake(0, 0);
myView.layer.shadowOpacity = 1;
- 换行连接字符:
NSString *str = @"数不清的漫山花朵"\\
"给这座大山添加了不少情趣";
NSLog(@"%@",str);
- 判断一个字符串中是否包含另外一个字符串:
NSString *str1 = @"abcqwqwq";
NSString *str2 = @"abc";
NSLog(@"%@", [str1 rangeOfString:str2].length != 0 ? @"包含" : @"不包含");
- 获取plist文件的数据:
NSString *path = [[NSBundle mainBundle]pathForResource:@"heros" ofType:@"plist"];
NSArray *array = [NSArray arrayWithContentsOfFile:path];
- nil文件的获取:
APPCell *cell = [[NSBundle mainBundle]loadNibNamed:@"" owner:nil options:nil].lastObject;
- 获取屏幕点击坐标:
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:touch.view];
NSLog(@"%@",NSStringFromCGPoint(point));
}
- 系统偏好存储的方式:
//1. NSUserDefaults简单实用:
// 创建偏好对象
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// 存值
[defaults setObject:@"daojiao" forKey:@"name"];
// 同步
[defaults synchronize];
// 取值
NSString *str = [defaults objectForKey:@"name"];
NSLog(@"%@",str);
// 2. NSUserDefaults图片存取:
[[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation([UIImage imageNamed:@"Default-568h@2xiPhonePortraitiOS78_320x568pt" ]) forKey:@"image"];
NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"image"];
self.imageView.image = [UIImage imageWithData:imageData];
- 定时器:
//第一种:
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(say) userInfo:nil repeats:YES];
//第二种:
CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(say)];
[link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
- 延时:
// 第一种:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
});
// 第二种:
[NSThread sleepForTimeInterval:2.0f];
// 第三种:
[self performSelector:self withObject:@selector(operation) afterDelay:1.0];
- 点击视图退出键盘:
第一种方式:
[textField resignFirstResponder];
第二种方式:
[self.view endEditing:YES];
- 将OC字符串转换成C字符:
sql.UTF8String
- 结构体循环:
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"第 %d 项内容是 %@", (int)idx, obj);
if ([@"王五" isEqualToString:obj]) *stop = YES;
}];
- 不使用HTTPS方法:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
- 随机数:
int x = arc4random() % 100;
//生成指定范围随机数[1-6]
int num = ((arc4random() % 6) + 1);
- 添加动画:
// 第一种:
[UIView animateWithDuration:2.0f animations:^{
//.. insert code
}];
// 第二种:
[UIView beginAnimations:@"doflip" context:nil];
//设置时常
[UIView setAnimationDuration:2.0f];
//设置动画淡入淡出
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
//设置代理
[UIView setAnimationDelegate:self];
//设置翻转方向
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
//动画结束
[UIView commitAnimations];
- arc和非arc的转换:
如果你的项目使用的非 ARC 模式,则为 ARC 模式的代码文件加入 -fobjc-arc 标签。
如果你的项目使用的是 ARC 模式,则为非 ARC 模式的代码文件加入 -fno-objc-arc 标签。
- Json(反序列化):
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
- URL中有特殊字符需要加百分号转译:
NSLog(@"%@",[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]);
// 取反
NSLog(@"%@",[str stringByRemovingPercentEncoding]);
- 局部刷新:
// 刷新指定行
NSIndexPath *path = [NSIndexPath indexPathForRow:alertView.tag inSection:0];
[self.tableview reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationRight];
//如果不进行刷新会怎么样?(修改之后不会即时刷新,要等到重新对cell进行数据填充的时候才会刷新)
- 屏幕自动旋转:
self.imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
- 获取系统版本:
[[UIDevice currentDevice].systemVersion doubleValue];
- 设置状态背景色:
// 第一种方式:
在info.plist文件中添加View controller-based status bar appearance 设为 NO
在AppDelegate.m 文件中的didFinishLaunchingWithOptionsfa方法中添加application.statusBarStyle = UIStatusBarStyleLightContent; 即可改变状态栏背景色。
总结:这种方法在ios9之前不会报错,但ios9后会报错,但不影响程序的正常运行,这是苹果自身的bug。
//第二种方式:在重写的UINavigationController控制器中添加一下代码
-(UIStatusBarStyle)preferredStatusBarStyle {
return UIStatusBarStyleLightContent;
}
总结:暂时能够解决问题,但目前不知解决的思路。
- 视图位置交换:
//把一个子视图放到最下面
[self.view sendSubviewToBack:view9];
//把一个子视图放到最上面
[self.view bringSubviewToFront:view9];
[self.view insertSubview:view10 atIndex:6];
//我们也可以指定插入在谁的下面,在view8下面,那就在最下面了
[self.view insertSubview:view10 belowSubview:view8];
//我们也可以指定插入在谁的上面,在view9上面,那就在最上面了
[self.view insertSubview:view10 aboveSubview:view9];
//我们也可以交换两个视图的位置,比如把5和7交换,也就是view8和view10
- 单击手势:
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImageView:)];
[cell addGestureRecognizer:singleTap];
- 设置导航栏主题:
// 通过navBar设置导航栏的所有属性,比如背景,字体大小...
UINavigationBar *navBar = [UINavigationBar appearance];
- 获取tabbar控制其中子控制器的个数:
self.viewControllers.count;
- 字体设置:
attr[NSForegroundColorAttributeName ] = [UIColor whiteColor];
attr[NSFontAttributeName] = [UIFont systemFontOfSize:20];
[navBar setTitleTextAttributes:attr];
- 隐藏tabbar:
viewController.hidesBottomBarWhenPushed = YES;
- 禁用系统自带侧滑:
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
- UIWebView填充html自动适配:
[webView setScalesPageToFit:YES];
- 获取设备类型:
[UIDevice currentDevice].model;
- 按钮存储多个值(Runtime):
#import <objc/runtime.h>
//存值:
objc_setAssociatedObject(btn, @"text", textf, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
//取值:
UITextField *t = objc_getAssociatedObject(button, @"text");
- 获取UIStoryboard中的控制器:
UIStoryboard *b = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
TwoViewController *two = [b instantiateViewControllerWithIdentifier:@"daili"];
- 返回不带状态栏的Rect:
CGRect bounds = [[UIScreen mainScreen] applicationFrame];
- iOS各种机型的屏幕适配问题以iPhone6P为基准:
#define SYRealValue(value) ((value)/414.0f*[UIScreen mainScreen].bounds.size.width)
- 数组转NSData:
NSArray *arr1 = [[NSArray alloc]initWithObjects:@"0",@"5",nil];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arr1];
NSArray *arr2 = [NSKeyedUnarchiver unarchiveObjectWithData:data];
- 获取项目路径:
$(SRCROOT):代表了工程的相对路径
$(PROJECT_NAME) :是相对工程名
- 获取APP下载地址:
https://itunes.apple.com/cn/app/idxxxxxxx?mt=8
将xxxxxxx替换成自己app ID
- 正则表达式使用:
NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
return [identityCardPredicate evaluateWithObject:str];
regex:验证的类型 (@"^(\\\\d{14}|\\\\d{17})(\\\\d|[xX])$")
str:需要验证的字符
- NSString 转 NSArray :
NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:[result dataUsingEncoding:NSUTF8StringEncoding];
options:0 error:NULL];
- 修改cell选中状态的背景:
cell.selectedBackgroundView
http://blog.csdn.net/a6472953/article/details/7532212
- TextField有值没值的判断::
_button.hidden = !(range.location > 0) && !(string.length == 1);
- 手机振动:
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
- 取消navigationbar下面的黑线:
self.navigationBar.barStyle = UIBaselineAdjustmentNone;
- 简单的二维动画操作:
self.testView.transform = CGAffineTransformMakeRotation(10*i); // 旋转
self.testView.transform = CGAffineTransformRotate(self.testView.transform, 1); // 可以承接上次动作,去操作。
self.testView.transform = CGAffineTransformTranslate(self.testView.transform, 0, 0);
self.testView.transform = CGAffineTransformMakeScale(i,i); // 放大
self.testView.transform=CGAffineTransformScale(self.testView.transform, 1, 1);
self.testView.transform = CGAffineTransformMakeTranslation(1,-100); // 平移
- 帧动画:
self.imageView.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"1"]
,[UIImage imageNamed:@"2"]
,[UIImage imageNamed:@"3"]
,[UIImage imageNamed:@"4"]
,[UIImage imageNamed:@"5"]
,nil];
self.imageView.animationDuration = 5.0;
self.imageView.animationRepeatCount = 3;
[self.imageView startAnimating];
- 获取某个view所在的控制器:
-(UIViewController *)viewController {
UIViewController *viewController = nil;
UIResponder *next = self.nextResponder;
while (next) {
if ([next isKindOfClass:[UIViewController class]]) {
viewController = (UIViewController *)next;
break;
}
next = next.nextResponder;
}
return viewController;
}
- 如何将IOS.m文件编译成C++:
// 打开 terminal 切换目录到需要转换的.m文件目录下,输入以下命令:
clang -rewrite-objc fileName.m
- 获取当前界面的View:
UIView *view = [[UIApplication sharedApplication].windows lastObject];
- 如何从A应用跳转到B应用::
//1.简单的跳转:
第一步:在B应用中配置URL Schemes
第二步:配置A应用访问B应用的NSURL *url = [NSURL URLWithString:@"weixin://"]; weixin就是B应用中配置URL Schemes参数。
第三步:在A应用中通过[[UIApplication sharedApplication] canOpenURL:url] 判断应用是否存在。
第四步:如果应用存在打开应用[[UIApplication sharedApplication] openURL:url];
备注:在执行第三步操作时,控制台可能打印错误信息,原因是苹果公司为了提高应用的安全性,想要访问必须设置对应白名单,白名单中最大允许50个应用被访问,如何设置白名单,
进入Info.plist文件中增加以下代码:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>weixin</string>
.....
</array>
// 2 .跳转传参数:
在简单的跳转的url中稍作修改:
URL配置:
NSURL *url = [NSURL URLWithString:@"weixin://www.shixueqian.com/abc?title=hello&content=helloworld"]; //打开url
在B应用的AppDelegate.m 文件中增加接收参数的代理就行:
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
NSLog(@"url=====%@ \\n sourceApplication=======%@ \\n annotation======%@", url, sourceApplication, annotation);
return YES;
}
IOS提供的代理:
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url ; //回调是在iOS2.0的时候推出的,参数只有url。
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation ;//B回到是在iOS4.2的时候推出的,参数有url sourceApplication annotation
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options NS_AVAILABLE_IOS(9_0);//B回到是在iOS4.2的时候推出的,参数有url sourceApplication annotation
- 通过运行时,置换两个方法执行顺序:
Method cell = class_getClassMethod([UITableView class], @selector(tableView:cellForRowAtIndexPath:));
Method cellHeight = class_getClassMethod([UITableView class], @selector(tableView:heightForRowAtIndexPath:));
method_exchangeImplementations(cell, cellHeight);
- 目录文件获取:
// 获取沙盒主目录路径
NSString *homeDir = NSHomeDirectory();
// 获取Documents目录路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
// 获取Caches目录路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];
// 获取tmp目录路径
NSString *tmpDir = NSTemporaryDirectory();
- 在一个字符串中查找另外一个字符是否存在:
[request.resourPath rangeOfString:@"?"].location == NSNotFound
- 数组去重的三个小技巧:
+(NSArrayExample *)shareManager {
static NSArrayExample *ae;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
ae = [[NSArrayExample alloc]init];
});
return ae;
}
+(NSArrayExample *)arrayRemove:(NSArray <NSString *> *)sourceArray arrayBlock:(void(^)(NSArray<NSString *> * _array))arrayBlock {
// 第一种方式 (有序) 利用NSMutableArray自带的containsObject方法检查重复值去重
// NSMutableArray *array = [[NSMutableArray alloc]initWithCapacity:sourceArray.count];
// for (NSString *value in sourceArray) {
// // 检查数组中是否包含该值
// if (![array containsObject:value]) {
// [array addObject:value];
// }
//
// 第二种方式(无序)利用NSMutableDictionary自身的特点,不能添加重复值达到去重,效率比第一种方式高
// NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithCapacity:sourceArray.count];
// for (NSString *value in sourceArray) {
// [dic setObject:value forKey:value];
// }
// NSArray *array = dic.allValues;
//
// 第三中方式(无序)和第二种方式一样的思路
NSSet *set = [NSSet setWithArray:sourceArray];
NSArray *array = [set allObjects];
if (array.count != 0 && array != nil) {
if (arrayBlock) {
arrayBlock(array);
}
}
return [self shareManager];
}
- 处理URL中包含中文字符:
//IOS8
[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//IOS9
[str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]
- 如何判断项目文件是否包含指定nib文件:
if ([[NSBundle mainBundle]pathForResource:self.identifiers[i] ofType:@"nib"] != nil) {
// ...code
}
- NSString转NSDate:
// 字符转日期 2016-12-15
+(NSDate *)charConvertDate:(NSString *) str{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"yyyy-MM-dd";
formatter.timeZone = [NSTimeZone defaultTimeZone];
NSDate *date = [formatter dateFromString:str];
return date;
}
- 将navigationbar 上的按钮靠边:
UIBarButtonItem * backBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.backButton];
UIBarButtonItem *space = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
space.width = -20;
viewController.navigationItem.leftBarButtonItems = @[space,backBarButtonItem];
}
- 获取某个view所在的控制器:
-(UIViewController *)viewController{ UIViewController *viewController = nil;
UIResponder *next = self.nextResponder;
while (next) {
if ([next isKindOfClass:[UIViewController class]]) {
viewController = (UIViewController *)next;
break;
}
next = next.nextResponder;
}
return viewController;
}
- 两种方法删除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];
}
- 打印系统所有已注册的字体名称:
void enumerateFonts()
{
for(NSString *familyName in [UIFont familyNames])
{
NSLog(@"%@",familyName);
NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
for(NSString *fontName in fontNames)
{
NSLog(@"\\t|- %@",fontName);
}
}
}
- 获取图片某一点的颜色:
-(UIColor*) getPixelColorAtLocation:(CGPoint)point inImage:(UIImage *)image
{
UIColor* color = nil;
CGImageRef inImage = image.CGImage;
CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage];
if (cgctx == NULL) {
return nil; /* error */
}
size_t w = CGImageGetWidth(inImage);
size_t h = CGImageGetHeight(inImage);
CGRect rect = {{0,0},{w,h}};
CGContextDrawImage(cgctx, rect, inImage);
unsigned char* data = CGBitmapContextGetData (cgctx);
if (data != NULL) {
int offset = 4*((w*round(point.y))+round(point.x));
int alpha = data[offset];
int red = data[offset+1];
int green = data[offset+2];
int blue = data[offset+3];
color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:
(blue/255.0f) alpha:(alpha/255.0f)];
}
CGContextRelease(cgctx);
if (data) {
free(data);
}
return color;
}
- 禁止锁屏:
[UIApplication sharedApplication].idleTimerDisabled = YES;
或
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
- iOS跳转到App Store下载应用评分:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];
- iOS 获取汉字的拼音:
+(NSString *)transform:(NSString *)chinese
{
//将NSString装换成NSMutableString
NSMutableString *pinyin = [chinese mutableCopy];
//将汉字转换为拼音(带音标)
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
NSLog(@"%@", pinyin);
//去掉拼音的音标
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
NSLog(@"%@", pinyin);
//返回最近结果
return pinyin;
}
- 获取实际使用的LaunchImage图片:
-(NSString *)getLaunchImageName
{
CGSize viewSize = self.window.bounds.size;
// 竖屏
NSString *viewOrientation = @"Portrait";
NSString *launchImageName = nil;
NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
for (NSDictionary* dict in imagesDict)
{
CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
{
launchImageName = dict[@"UILaunchImageName"];
}
}
return launchImageName;
} }
- NSArray 快速求总和 最大值 最小值 和 平均值:
NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%f\\n%f\\n%f\\n%f",sum,avg,max,min);
- NSDateFormatter的格式:
G: 公元时代,例如AD公元
yy: 年的后2位
yyyy: 完整年
MM: 月,显示为1-12
MMM: 月,显示为英文月份简写,如 Jan
MMMM: 月,显示为英文月份全称,如 Janualy
dd: 日,2位数表示,如02
d: 日,1-2位显示,如 2
EEE: 简写星期几,如Sun
EEEE: 全写星期几,如Sunday
aa: 上下午,AM/PM
H: 时,24小时制,0-23
K:时,12小时制,0-11
m: 分,1-2位
mm: 分,2位
s: 秒,1-2位
ss: 秒,2位
S: 毫秒
- #324a23颜色转USColor:
+(UIColor *) stringTOColor:(NSString *)str
{
if (!str || [str isEqualToString:@""]) {
return nil;
}
unsigned red,green,blue;
NSRange range;
range.length = 2;
range.location = 1;
[[NSScanner scannerWithString:[str substringWithRange:range]] scanHexInt:&red];
range.location = 3;
[[NSScanner scannerWithString:[str substringWithRange:range]] scanHexInt:&green];
range.location = 5;
[[NSScanner scannerWithString:[str substringWithRange:range]] scanHexInt:&blue];
UIColor *color= [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:1];
return color;
}
- 获取当前视图:
[[UIApplication sharedApplication].windows lastObject]
总结:
文章后续还会更新。文章中可能存在错别字或者理解不到位的地方,欢迎挑刺,如果你也是一枚IOS爱好者,请加入我们的QQ群:126440594,一起分享,一起成长。