最近逛论坛的时候,发现一篇很不错的总结博客,里面总结了不少实用的代码语法,摘抄一部分记录下来,以备不时之需。
1、禁止手机睡眠
[UIApplication sharedApplication].idleTimerDisabled = YES;
2、去除数组中重复的对象
NSArray *newArr = [oldArr valueForKeyPath:@“@distinctUnionOfObjects.self"];
3、跳进app权限设置
if (UIApplicationOpenSettingsURLString != NULL) {
UIApplication *application = [UIApplication sharedApplication];
NSURL *URL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
[application openURL:URL options:@{}
completionHandler:nil];
} else {
[application openURL:URL];
}
}
4、collectionView的内容小于其宽高的时候是不能滚动的,设置可以滚动:
collectionView.alwaysBounceHorizontal = YES;
collectionView.alwaysBounceVertical = YES;
5、设置navigationBar上的title颜色和大小
[self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor youColor], NSFontAttributeName : [UIFont systemFontOfSize:15]}];
6、颜色转图片
+ (UIImage *)cl_imageWithColor:(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 *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
7、强/弱引用
#define WeakSelf(type) __weak typeof(type) weak##type = type; // weak
#define StrongSelf(type) __strong typeof(type) type = weak##type; // strong
8、由角度转换弧度 、 由弧度转换角度
#define DegreesToRadian(x) (M_PI * (x) / 180.0) //角度转弧度
#define RadianToDegrees(radian) (radian*180.0)/(M_PI) //弧度转角度
9、获取沙盒 Document
#define PathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
10、获取沙盒 Cache
#define PathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]
11、自定义NSLog
#ifdef DEBUG
#define NSLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define NSLog(...)
#endif
12、字体大小Font
#define FontL(s) [UIFont systemFontOfSize:s weight:UIFontWeightLight]
#define FontR(s) [UIFont systemFontOfSize:s weight:UIFontWeightRegular]
#define FontB(s) [UIFont systemFontOfSize:s weight:UIFontWeightBold]
#define FontT(s) [UIFont systemFontOfSize:s weight:UIFontWeightThin]
#define Font(s) FontL(s)
13、修改textField的placeholder的字体颜色、大小
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
14、统一收起键盘
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
15、控制屏幕旋转,在控制器中写
/** 是否支持自动转屏 */
- (BOOL)shouldAutorotate {
return YES;
}
/** 支持哪些屏幕方向 */
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
}
/** 默认的屏幕方向(当前ViewController必须是通过模态出来的UIViewController(模态带导航的无效)方式展现出来的,才会调用这个方法) */
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return UIInterfaceOrientationLandscapeLeft | UIInterfaceOrientationLandscapeRight;
}
16、获取app缓存大小
- (CGFloat)getCachSize {
NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] getSize];
//获取自定义缓存大小
//用枚举器遍历 一个文件夹的内容
//1.获取 文件夹枚举器
NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:myCachePath];
__block NSUInteger count = 0;
//2.遍历
for (NSString *fileName in enumerator) {
NSString *path = [myCachePath stringByAppendingPathComponent:fileName];
NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
count += fileDict.fileSize;//自定义所有缓存大小
}
// 得到是字节 转化为M
CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024;
return totalSize;
}
17、清理app缓存
- (void)handleClearView {
//删除两部分
//1.删除 sd 图片缓存
//先清除内存中的图片缓存
[[SDImageCache sharedImageCache] clearMemory];
//清除磁盘的缓存
[[SDImageCache sharedImageCache] clearDisk];
//2.删除自己缓存
NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
[[NSFileManager defaultManager] removeItemAtPath:myCachePath error:nil];
}
18、判断图片类型
//通过图片Data数据第一个字节 来获取图片扩展名
- (NSString *)contentTypeForImageData:(NSData *)data
{
uint8_t c;
[data getBytes:&c length:1];
switch (c)
{
case 0xFF:
return @"jpeg";
case 0x89:
return @"png";
case 0x47:
return @"gif";
case 0x49:
case 0x4D:
return @"tiff";
case 0x52:
if ([data length] < 12) {
return nil;
}
NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
if ([testString hasPrefix:@"RIFF"]
&& [testString hasSuffix:@"WEBP"])
{
return @"webp";
}
return nil;
}
return nil;
}
19、导入自定义字体库
1、找到你想用的字体的 ttf 格式,拖入工程
2、在工程的plist中增加一行数组,“Fonts provided by application”
3、为这个key添加一个item,value为你刚才导入的ttf文件名
4、直接使用即可:label.font = [UIFont fontWithName:@"你刚才导入的ttf文件名" size:20.0];
20、KVO监听某个对象的属性
// 添加监听者
[self addObserver:self forKeyPath:property options:NSKeyValueObservingOptionNew context:nil];
// 当监听的属性值变化的时候会来到这个方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"property"]) {
[self textViewTextChange];
} else {
}
}
21、透明颜色不影响子视图透明度
[UIColor colorWithRed:<#(CGFloat)#> green:<#(CGFloat)#> blue:<#(CGFloat)#> alpha:<#(CGFloat)#>];
22、合并两个图片
+ (UIImage*)mergeImage:(UIImage*)firstImage withImage:(UIImage*)secondImage {
CGImageRef firstImageRef = firstImage.CGImage;
CGFloat firstWidth = CGImageGetWidth(firstImageRef);
CGFloat firstHeight = CGImageGetHeight(firstImageRef);
CGImageRef secondImageRef = secondImage.CGImage;
CGFloat secondWidth = CGImageGetWidth(secondImageRef);
CGFloat secondHeight = CGImageGetHeight(secondImageRef);
CGSize mergedSize = CGSizeMake(MAX(firstWidth, secondWidth), MAX(firstHeight, secondHeight));
UIGraphicsBeginImageContext(mergedSize);
[firstImage drawInRect:CGRectMake(0, 0, firstWidth, firstHeight)];
[secondImage drawInRect:CGRectMake(0, 0, secondWidth, secondHeight)];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
23、画水印
// 画水印
- (void) setImage:(UIImage *)image withWaterMark:(UIImage *)mark inRect:(CGRect)rect
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0)
{
UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0);
}
//原图
[image drawInRect:self.bounds];
//水印图
[mark drawInRect:rect];
UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.image = newPic;
}
24、让label的文字内容显示在左上/右上/左下/右下/中心顶/中心底部
自定义UILabel
// 重写label的textRectForBounds方法
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
CGRect rect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
switch (self.textAlignmentType) {
case WZBTextAlignmentTypeLeftTop: {
rect.origin = bounds.origin;
}
break;
case WZBTextAlignmentTypeRightTop: {
rect.origin = CGPointMake(CGRectGetMaxX(bounds) - rect.size.width, bounds.origin.y);
}
break;
case WZBTextAlignmentTypeLeftBottom: {
rect.origin = CGPointMake(bounds.origin.x, CGRectGetMaxY(bounds) - rect.size.height);
}
break;
case WZBTextAlignmentTypeRightBottom: {
rect.origin = CGPointMake(CGRectGetMaxX(bounds) - rect.size.width, CGRectGetMaxY(bounds) - rect.size.height);
}
break;
case WZBTextAlignmentTypeTopCenter: {
rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, CGRectGetMaxY(bounds) - rect.origin.y);
}
break;
case WZBTextAlignmentTypeBottomCenter: {
rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, CGRectGetMaxY(bounds) - CGRectGetMaxY(bounds) - rect.size.height);
}
break;
case WZBTextAlignmentTypeLeft: {
rect.origin = CGPointMake(0, rect.origin.y);
}
break;
case WZBTextAlignmentTypeRight: {
rect.origin = CGPointMake(rect.origin.x, 0);
}
break;
case WZBTextAlignmentTypeCenter: {
rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, (CGRectGetHeight(bounds) - CGRectGetHeight(rect)) / 2);
}
break;
default:
break;
}
return rect;
}
- (void)drawTextInRect:(CGRect)rect {
CGRect textRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
[super drawTextInRect:textRect];
}
25、scrollView上的输入框,键盘挡住的问题
推荐用IQKeyboardManager这个框架!
手动解决如下
1、监听键盘弹出/消失的通知
2、在通知中加入代码:
NSDictionary* info = [aNotification userInfo];
CGRect keyPadFrame=[[UIApplication sharedApplication].keyWindow convertRect:[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue] fromView:self.view];
CGSize kbSize =keyPadFrame.size;
CGRect activeRect=[self.view convertRect:activeField.frame fromView:activeField.superview];
CGRect aRect = self.view.bounds;
aRect.size.height -= (kbSize.height);
CGPoint origin = activeRect.origin;
origin.y -= backScrollView.contentOffset.y;
if (!CGRectContainsPoint(aRect, origin)) {
CGPoint scrollPoint = CGPointMake(0.0,CGRectGetMaxY(activeRect)-(aRect.size.height));
[backScrollView setContentOffset:scrollPoint animated:YES];
}
26、字符串是否为空
+ (BOOL)isEqualToNil:(NSString *)str {
return str.length <= 0 || [str isEqualToString:@""] || !str;
}
27、当tableView占不满一屏时,去除下边多余的单元格
self.tableView.tableHeaderView = [UIView new];
self.tableView.tableFooterView = [UIView new];
28、isKindOfClass和isMemberOfClass的区别
isKindOfClass可以判断某个对象是否属于某个类,或者这个类的子类。
isMemberOfClass更加精准,它只能判断这个对象类型是否为这个类(不能判断子类)
29、将tableView滚动到顶部
[tableView setContentOffset:CGPointZero animated:YES];
或者
[tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
30、禁用系统滑动返回功能
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = nil;
}
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
return NO;
}
31、scrollView滚动到最下边
CGPoint bottomOffset = CGPointMake(0, scrollView.contentSize.height - scrollView.bounds.size.height);
[scrollView setContentOffset:bottomOffset animated:YES];
32、UIView背景颜色渐变
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
[self.view addSubview:view];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[view.layer insertSublayer:gradient atIndex:0];
33、将一个view放置在其兄弟视图的最上面/最下面
[parentView bringSubviewToFront:yourView] //最上面
[parentView sendSubviewToBack:yourView] //最下面
34、让手机震动一下
倒入框架
#import <AudioToolbox/AudioToolbox.h>
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
或者
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
35、摇一摇功能
1、打开摇一摇功能
[UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
2、让需要摇动的控制器成为第一响应者
[self becomeFirstResponder];
3、实现以下方法
// 开始摇动
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
// 取消摇动
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
// 摇动结束
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
36、在非ViewController的地方弹出UIAlertController对话框
// 最好抽成一个分类
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"message" preferredStyle:UIAlertControllerStyleAlert];
//...
id rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
if([rootViewController isKindOfClass:[UINavigationController class]])
{
rootViewController = ((UINavigationController *)rootViewController).viewControllers.firstObject;
}
if([rootViewController isKindOfClass:[UITabBarController class]])
{
rootViewController = ((UITabBarController *)rootViewController).selectedViewController;
}
[rootViewController presentViewController:alertController animated:YES completion:nil];
37、判断NSDate是不是今天
NSDateComponents *otherDay = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
NSDateComponents *today = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
if([today day] == [otherDay day] &&
[today month] == [otherDay month] &&
[today year] == [otherDay year] &&
[today era] == [otherDay era]) {
// 是今天
}
38、tableViewCell分割线顶到头
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
[cell setSeparatorInset:UIEdgeInsetsZero];
[cell setLayoutMargins:UIEdgeInsetsZero];
cell.preservesSuperviewLayoutMargins = NO;
}
- (void)viewDidLayoutSubviews {
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
[self.tableView setLayoutMargins:UIEdgeInsetsZero];
}
最后附上原文的连接:http://www.jianshu.com/p/1ff9e44ccc78