iOS開發小技巧合集
阿新 • • 發佈:2018-11-29
本文主要記錄日常工作中積累的一些iOS小技巧
- SDWebImage 載入大量高清圖片時記憶體暴增
- 解決方案:關閉SD載入高清大圖時的解壓縮
static BOOL SDImageCacheOldShouldDecompressImages = YES;
static BOOL SDImagedownloderOldShouldDecompressImages = YES;
- (void)viewDidLoad {
[super viewDidLoad];
// 關閉SD載入高清大圖時的解壓縮
SDImageCache *canche = [SDImageCache sharedImageCache];
SDImageCacheOldShouldDecompressImages = canche.shouldDecompressImages;
canche.shouldDecompressImages = NO;
SDWebImageDownloader *downloder = [SDWebImageDownloader sharedDownloader];
SDImagedownloderOldShouldDecompressImages = downloder.shouldDecompressImages;
downloder.shouldDecompressImages = NO;
}
-(void)dealloc {
SDImageCache *canche = [SDImageCache sharedImageCache];
canche.shouldDecompressImages = SDImageCacheOldShouldDecompressImages;
SDWebImageDownloader *downloder = [SDWebImageDownloader sharedDownloader];
downloder.shouldDecompressImages = SDImagedownloderOldShouldDecompressImages;
}
複製程式碼
-
SDWebImage本地快取有時候會害人。如果之前快取過一張圖片,即使下次伺服器換了這張圖片,但是圖片url沒換,用SDWebimage下載下來的還是以前那張,所以遇到這種問題,不要先去懟伺服器,清空下快取再試就好了。
-
禁止手機睡眠
[UIApplication sharedApplication].idleTimerDisabled = YES;
複製程式碼
- 隱藏某行cell
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 如果是你需要隱藏的那一行,返回高度為0
if (indexPath.row == YouWantToHideRow){
return 0;
}
return 44;
}
// 然後再你需要隱藏cell的時候呼叫
[self.tableView beginUpdates];
[self.tableView endUpdates];
複製程式碼
- 禁用button高亮
button.adjustsImageWhenHighlighted = NO;
或者在建立的時候
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
複製程式碼
- 動畫切換window的根控制器
[UIView transitionWithView:[UIApplication sharedApplication].keyWindow duration:.5f
options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
BOOL oldState = [UIView areAnimationsEnabled];
[UIView setAnimationsEnabled:NO];
[UIApplication sharedApplication].keyWindow.rootViewController = [[RootViewController alloc]init];
[UIView setAnimationsEnabled:oldState];
} completion:^(BOOL finished) {
}];
複製程式碼
- 去除陣列中重複的物件
NSArray *newArr = [oldArr valueForKeyPath:@"@distinctUnionOfObjects.self"];
複製程式碼
-
編譯的時候遇到 no such file or directory: /users/apple/XXX
- 是因為編譯的時候,在此路徑下找不到這個檔案,解決這個問題,首先是是要檢查缺少的檔案是不是在工程中,如果不在工程中,需要從本地拖進去,如果發現已經存在工程中了,或者拖進去還是報錯,這時候需要去build phases中搜索這個檔案,這時候很可能會搜出現兩個相同的檔案,這時候,有一個路徑是正確的,刪除另外一個即可。如果刪除了還是不行,需要把兩個都刪掉,然後重新往工程裡拖進這個檔案即可
-
iOS8系統中,tableView最好實現下-tableView: heightForRowAtIndexPath:這個代理方法,要不然在iOS8中可能就會出現顯示不全或者無法響應事件的問題
-
iOS8中實現側滑功能的時候這個方法必須實現,要不然在iOS8中無法側滑
// 必須寫的方法,和editActionsForRowAtIndexPath配對使用,裡面什麼不寫也行
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
}
複製程式碼
- 三個比較特殊的通知
NSSystemTimeZoneDidChangeNotification監聽修改時間介面的兩個按鈕狀態變化
UIApplicationSignificantTimeChangeNotification 監聽使用者改變時間 (只要點選自動設定按鈕就會呼叫)
NSSystemClockDidChangeNotification 監聽使用者修改時間(時間不同才會呼叫)
複製程式碼
- 獲取不到UICollectionView指定cell的問題
[self.collectionView layoutIfNeeded];//新增這句話就好
QTMResContinueEditeCell *cell = (QTMResContinueEditeCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:_index inSection:0]];
複製程式碼
- 跳進app許可權設定
// 跳進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];
}
}
複製程式碼
- 給一個view截圖
- (UIImage *)cutImageWithView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
複製程式碼
-
注意物件為nil的時候,呼叫此物件分類的方法不會執行
-
collectionView的內容小於其寬高的時候是不能滾動的,設定可以滾動:
collectionView.alwaysBounceHorizontal = YES;
collectionView.alwaysBounceVertical = YES;
複製程式碼
- 顏色轉圖片
+ (UIImage *)imageWithColor:(UIColor *)color {
//描述一個矩形
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
//開啟圖形上下文
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
//獲得圖形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
//使用color演示填充上下文
CGContextSetFillColorWithColor(ctx, [color CGColor]);
//渲染上下文
CGContextFillRect(ctx, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//關閉圖形上下文
UIGraphicsEndImageContext();
return image;
}
複製程式碼
- view設定圓角
#define ViewBorderRadius(View, Radius, Width, Color)\
\
[View.layer setCornerRadius:(Radius)];\
[View.layer setMasksToBounds:YES];\
[View.layer setBorderWidth:(Width)];\
[View.layer setBorderColor:[Color CGColor]] // view圓角
複製程式碼
- view某個角度設定圓角
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.whiteView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.whiteView.bounds;
maskLayer.path = maskPath.CGPath;
self.whiteView.layer.mask = maskLayer;
##指定了需要成為圓角的角該引數是UIRectCorner型別的,可選的值有:
* UIRectCornerTopLeft
* UIRectCornerTopRight
* UIRectCornerBottomLeft
* UIRectCornerBottomRight
* UIRectCornerAllCorners
複製程式碼
- 由角度轉換弧度
#define DegreesToRadian(x) (M_PI * (x) / 180.0)
複製程式碼
- 由弧度轉換角度
#define RadianToDegrees(radian) (radian*180.0)/(M_PI)
複製程式碼
- 獲取圖片資源
//建議使用前兩種巨集定義,效能高於後者
#define LOADIMAGE(file,ext) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:file ofType:ext]]
#define IMAGE(A) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:A ofType:nil]]
#define ImageNamed(_pointer) [UIImage imageNamed:[UIUtil imageName:_pointer]]
#define UIImageName(name) [UIImage imageNamed:name]
複製程式碼
- 檔案路徑
//獲取temp
#define PathTemp NSTemporaryDirectory()
//獲取Document
#define PathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
//獲取 Cache
#define PathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]
複製程式碼
- GCD程式碼只執行一次
#define kDISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken;
dispatch_once(&onceToken, onceBlock);
複製程式碼
- 自定義NSLog
//DEBUG 模式下列印日誌,當前行
#ifdef DEBUG
# define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
# define DLog(...)
#endif
//重寫NSLog,Debug模式下列印日誌和當前行數
#if DEBUG
#define NSLog(FORMAT, ...) fprintf(stderr,"\nfunction:%s line:%d content:%s\n", __FUNCTION__, __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
#define NSLog(FORMAT, ...) nil
#endif
//DEBUG 模式下列印日誌,當前行 並彈出一個警告
#ifdef DEBUG
# define ULog(fmt, ...) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%s\n [Line %d] ", __PRETTY_FUNCTION__, __LINE__] message:[NSString stringWithFormat:fmt, ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; }
#else
# define ULog(...)
#endif
複製程式碼
- Font
#define FONTS(size) [UIFont systemFontOfSize:(size)]
#define BOLDFONTS(size) [UIFont boldSystemFontOfSize:(size)]
複製程式碼
- GCD
//主執行緒
#define kDISPATCH_MAIN_THREAD(mainQueueBlock) dispatch_async(dispatch_get_main_queue(), mainQueueBlock);
//非同步執行緒
#define kDISPATCH_GLOBAL_QUEUE_DEFAULT(globalQueueBlock) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), globalQueueBlocl);
複製程式碼
- 通知
#define NOTIF_ADD(n, f) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(f) name:n object:nil]
#define NOTIF_POST(n, o) [[NSNotificationCenter defaultCenter] postNotificationName:n object:o]
#define NOTIF_REMV() [[NSNotificationCenter defaultCenter] removeObserver:self]
複製程式碼
- Color
// RGB顏色轉換(16進位制->10進位制)
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
// 獲取RGB顏色
#define RGBA(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
//清除背景色
#define CLEARCOLOR [UIColor clearColor]
// 隨機色
#define RandomCOLOR RGBCOLOR(arc4random_uniform(256),arc4random_uniform(256),arc4random_uniform(256))
複製程式碼
- 獲取window
+(UIWindow*)getWindow {
UIWindow* win = nil; //[UIApplication sharedApplication].keyWindow;
for (id item in [UIApplication sharedApplication].windows) {
if ([item class] == [UIWindow class]) {
if (!((UIWindow*)item).hidden) {
win = item;
break;
}
}
}
return win;
}
複製程式碼
- 修改textField的placeholder的字型顏色、大小
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
// 或者
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholder attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13],NSForegroundColorAttributeName : [UIColor grayColor]}];
複製程式碼
- APP快取
/** * 存 陣列資料*/
+(void)setObectOfArray:(NSArray *)array fileName:(NSString *)fileName
{
//快取檔案的 根路徑
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
// 快取 資料夾 路徑
NSString *filePath = [path stringByAppendingPathComponent:@"XXX.dataCache"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:filePath] == NO)
{
[fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
}
//快取檔案的路徑
NSString * cacheFilePath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",fileName]];
BOOL isSuccess = [array writeToFile:cacheFilePath atomically:NO];
if (isSuccess) {
NSLog(@"快取資料成功:---%@",cacheFilePath);
}else
{
NSLog(@"快取資料失敗:---%@",cacheFilePath);
}
}
/*** 取 陣列資料*/
+(NSArray *)cacheArrayForFileName:(NSString *)fileName
{
//快取檔案的 根路徑
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
// 快取 資料夾 路徑
NSString *filePath = [path stringByAppendingPathComponent:@"XXX.dataCache"];
//快取檔案的路徑
NSString * cacheFilePath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",fileName]];
//取得快取檔案
NSArray *array = [NSArray arrayWithContentsOfFile:cacheFilePath];
return array;
}
/*** 清除 這個全部的快取資料 */
+(void)clearCacheListData:(void (^)())completion
{
// 異執行緒
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 清楚快取
//快取檔案的 根路徑
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
// 快取 資料夾 路徑
NSString *filePath = [path stringByAppendingPathComponent:@"FortuneDonkey.dataCache"];
NSFileManager *manager = [NSFileManager defaultManager];
//移除資料夾
[manager removeItemAtPath:filePath error:nil];
// 建立一個新的資料夾
[manager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
if (completion)
{
//回撥主執行緒
dispatch_async(dispatch_get_main_queue(), ^{
completion();
});
}
});
}
/*** 清除SD快取資料 */
-(void)clearSDCacheData
{
//先清除記憶體中的圖片快取
[[SDImageCache sharedImageCache] clearMemory];
//清除磁碟的快取
[[SDImageCache sharedImageCache] clearDisk];
}
複製程式碼
- 獲取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;
}
複製程式碼
- 幾個常用許可權判斷
if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
NSLog(@"沒有定位許可權");
}
AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (statusVideo == AVAuthorizationStatusDenied) {
NSLog(@"沒有攝像頭許可權");
}
//是否有麥克風許可權
AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
if (statusAudio == AVAuthorizationStatusDenied) {
NSLog(@"沒有錄音許可權");
}
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusDenied) {
NSLog(@"沒有相簿許可權");
}
}];
複製程式碼
- 系統相關的一些方法
//獲取系統版本
#define IOS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
#define IS_IOS10_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0)
//獲取當前語言
#define CurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])
//判斷是否 Retina屏、裝置是否%fhone 5、是否是iPad
#define isRetina ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhone6 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) : NO)
#define isPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
//判斷是真機還是模擬器
#if TARGET_OS_IPHONE
//iPhone Device
#endif
#if TARGET_IPHONE_SIMULATOR
//iPhone Simulator
#endif
複製程式碼
- 長按複製功能
- (void)viewDidLoad
{
[self.view addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pasteBoard:)]];
}
- (void)pasteBoard:(UILongPressGestureRecognizer *)longPress {
if (longPress.state == UIGestureRecognizerStateBegan) {
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = @"我是文字";
}
}
複製程式碼
- 判斷圖片型別
//通過圖片 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;
}
複製程式碼
- 獲取手機和 APP 資訊
//手機序列號
NSString* identifierNumber = [[UIDevice currentDevice] uniqueIdentifier];
//手機別名: 使用者定義的名稱
NSString* userPhoneName = [[UIDevice currentDevice] name];
//裝置名稱
NSString* deviceName = [[UIDevice currentDevice] systemName];
//手機系統版本
NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
//手機型號
NSString* phoneModel = [[UIDevice currentDevice] model];
//地方型號 (國際化區域名稱)
NSString* localPhoneModel = [[UIDevice currentDevice] localizedModel];
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
// 當前應用名稱
NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
// 當前應用版本
NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
// 當前應用版本號碼 int型別
NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
複製程式碼
- UIImage繪製圓角
- (UIImage *)circleImage
{
// NO代表透明
UIGraphicsBeginImageContextWithOptions(self.size, NO, 1);
// 獲得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 新增一個圓
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
// 方形變圓形
CGContextAddEllipseInRect(ctx, rect);
// 裁剪
CGContextClip(ctx);
// 將圖片畫上去
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
複製程式碼
- 準確獲取圖片畫素
CGFloat fixelW = CGImageGetWidth(image.CGImage);
CGFloat fixelH = CGImageGetHeight(image.CGImage);
複製程式碼
- JSON字串轉字典
+ (NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
return responseJSON;
}
複製程式碼
- 獲取當前控制器
//獲取當前螢幕顯示的viewcontroller
- (UIViewController *)getCurrentVC{
UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
if (!window) {
return nil;
}
UIView *tempView;
for (UIView *subview in window.subviews) {
if ([[subview.classForCoder description] isEqualToString:@"UILayoutContainerView"]) {
tempView = subview;
break;
}
}
if (!tempView) {
tempView = [window.subviews lastObject];
}
id nextResponder = [tempView nextResponder];
while (![nextResponder isKindOfClass:[UIViewController class]] || [nextResponder isKindOfClass:[UINavigationController class]] || [nextResponder isKindOfClass:[UITabBarController class]]) {
tempView = [tempView.subviews firstObject];
if (!tempView) {
return nil;
}
nextResponder = [tempView nextResponder];
}
return (UIViewController *)nextResponder;
}
複製程式碼
- 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 {
}
}
複製程式碼
- Reachability判斷網路狀態
NetworkStatus status = [[Reachability reachabilityForInternetConnection] currentReachabilityStatus];
if (status == NotReachable) {
NSLog(@"當前裝置無網路");
}
if (status == ReachableViaWiFi) {
NSLog(@"當前wifi網路");
}
if (status == ReachableViaWWAN) {
NSLog(@"當前蜂窩行動網路");
}
複製程式碼
- AFNetworking監聽網路狀態
// 監聽網路狀況
AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
[mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusUnknown:
break;
case AFNetworkReachabilityStatusNotReachable: {
NSLog(@"當前裝置無網路");
}
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"當前wifi網路");
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"當前蜂窩行動網路");
break;
default:
break;
}
}];
[mgr startMonitoring];
複製程式碼
- 父檢視透明不影響子檢視的做法
self.view.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0.7f];
複製程式碼
- 取圖片某一點的顏色
if (point.x < 0 || point.y < 0) return nil;
CGImageRef imageRef = self.CGImage;
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
if (point.x >= width || point.y >= height) return nil;
unsigned char *rawData = malloc(height * width * 4);
if (!rawData) return nil;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData,
width,
height,
bitsPerComponent,
bytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast
| kCGBitmapByteOrder32Big);
if (!context) {
free(rawData);
return nil;
}
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
int byteIndex = (bytesPerRow * point.y) + point.x * bytesPerPixel;
CGFloat red = (rawData[byteIndex] * 1.0) / 255.0;
CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0;
CGFloat blue = (rawData[byteIndex + 2] * 1.0) / 255.0;
CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;
UIColor *result = nil;
result = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
free(rawData);
return result;
複製程式碼
- 判斷該圖片是否有透明度通道
- (BOOL)hasAlphaChannel
{
CGImageAlphaInfo alpha = CGImageGetAlphaInfo(self.CGImage);
return (alpha == kCGImageAlphaFirst ||
alpha == kCGImageAlphaLast ||
alpha == kCGImageAlphaPremultipliedFirst ||
alpha == kCGImageAlphaPremultipliedLast);
}
複製程式碼
- 兩張圖片合成
+ (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;
}
複製程式碼
- 製作水印
// 畫水印
- (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;
}
複製程式碼
- 讓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];
}
複製程式碼
- 移除字串中的空格和換行
+ (NSString *)removeSpaceAndNewline:(NSString *)str {
NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
return temp;
}
複製程式碼
- 判斷字串中是否有空格
+ (BOOL)isBlank:(NSString *)str {
NSRange _range = [str rangeOfString:@" "];
if (_range.location != NSNotFound) {
//有空格
return YES;
} else {
//沒有空格
return NO;
}
}
複製程式碼
- 獲取一個視訊的第一幀圖片
NSURL *url = [NSURL URLWithString:filepath];
AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
generate1.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 2);
CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
UIImage *one = [[UIImage alloc] initWithCGImage:oneRef];
return one;
複製程式碼
- 獲取視訊的時長
+ (NSInteger)getVideoTimeByUrlString:(NSString *)urlString {
NSURL *videoUrl = [NSURL URLWithString:urlString];
AVURLAsset *avUrl = [AVURLAsset assetWithURL:videoUrl];
CMTime time = [avUrl duration];
int seconds = ceil(time.value/time.timescale);
return seconds;
}
複製程式碼
- 當tableView佔不滿一屏時,去除下邊多餘的單元格
self.tableView.tableHeaderView = [UIView new];
self.tableView.tableFooterView = [UIView new];
複製程式碼
- isKindOfClass和isMemberOfClass的區別
isKindOfClass可以判斷某個物件是否屬於某個類,或者這個類的子類。
isMemberOfClass更加精準,它只能判斷這個物件型別是否為這個類(不能判斷子類)
複製程式碼
- 禁用系統滑動返回功能
- (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;
}
複製程式碼
- UILabel設定內邊距
子類化UILabel,重寫drawTextInRect方法
- (void)drawTextInRect:(CGRect)rect {
// 邊距,上左下右
UIEdgeInsets insets = {0, 5, 0, 5};
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
複製程式碼
- UILabel設定文字描邊
子類化UILabel,重寫drawTextInRect方法
- (void)drawTextInRect:(CGRect)rect
{
CGContextRef c = UIGraphicsGetCurrentContext();
// 設定描邊寬度
CGContextSetLineWidth(c, 1);
CGContextSetLineJoin(c, kCGLineJoinRound);
CGContextSetTextDrawingMode(c, kCGTextStroke);
// 描邊顏色
self.textColor = [UIColor redColor];
[super drawTextInRect:rect];
// 文字顏色
self.textColor = [UIColor yellowColor];
CGContextSetTextDrawingMode(c, kCGTextFill);
[super drawTextInRect:rect];
}
複製程式碼
- UIView背景顏色漸變
+ (CAGradientLayer *)setGradualChangingColor:(UIView *)view fromColor:(NSString *)fromHexColorStr toColor:(NSString *)toHexColorStr{
// CAGradientLayer類對其繪製漸變背景顏色、填充層的形狀(包括圓角)
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = view.bounds;
// 建立漸變色陣列,需要轉換為CGColor顏色
gradientLayer.colors = @[(__bridge id)[UIColor colorWithHexString:fromHexColorStr].CGColor,(__bridge id)[UIColor colorWithHexString:toHexColorStr].CGColor];
// 設定漸變顏色方向,左下點為(0,0), 右上點為(1,1)
gradientLayer.startPoint = CGPointMake(0, 0.5);
gradientLayer.endPoint = CGPointMake(1, 0.5);
// 設定顏色變化點,取值範圍 0.0~1.0
gradientLayer.locations = @[@0,@1];
return gradientLayer;
}
複製程式碼
- UIView某個角新增圓角
// 左上角和右下角新增圓角
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomRight) cornerRadii:CGSizeMake(20, 20)];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = view.bounds;
maskLayer.path = maskPath.CGPath;
view.layer.mask = maskLayer;
複製程式碼
- UIImage和base64互轉
// view分類方法
- (NSString *)encodeToBase64String:(UIImage *)image {
return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
return [UIImage imageWithData:data];
}
複製程式碼
- UIWebView設定背景透明
[webView setBackgroundColor:[UIColor clearColor]];
[webView setOpaque:NO];
複製程式碼
- 設定tableView分割線顏色以及頂到頭
// 分割線顏色
[self.tableView setSeparatorColor:[UIColor myColor]];
// 頂到頭
- (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];
}
複製程式碼
- 為一個view新增虛線邊框
CAShapeLayer *border = [CAShapeLayer layer];
border.strokeColor = [UIColor colorWithRed:67/255.0f green:37/255.0f blue:83/255.0f alpha:1].CGColor;
border.fillColor = nil;
border.lineDashPattern = @[@4, @2];
border.path = [UIBezierPath bezierPathWithRect:view.bounds].CGPath;
border.frame = view.bounds;
[view.layer addSublayer:border];
複製程式碼
- UITextView中開啟或禁用複製,剪下,選擇,全選等功能
// 繼承UITextView重寫這個方法
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
// 返回NO為禁用,YES為開啟
// 貼上
if (action == @selector(paste:)) return NO;
// 剪下
if (action == @selector(cut:)) return NO;
// 複製
if (action == @selector(copy:)) return NO;
// 選擇
if (action == @selector(select:)) return NO;
// 選中全部
if (action == @selector(selectAll:)) return NO;
// 刪除
if (action == @selector(delete:)) return NO;
// 分享
if (action == @selector(share)) return NO;
return [super canPerformAction:action withSender:sender];
}
複製程式碼