iOS 一些開發(fā)中可能會用到的方法總結,持續(xù)更新

1.判斷是否含有非法字符

+ (BOOL)JudgeTheillegalCharacter:(NSString *)content{

? ? NSString *str =@"^[A-Za-z0-9\\u4e00-\u9fa5]+$";

? ? NSPredicate* emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];

? ? if (![emailTest evaluateWithObject:content]) {

? ? ? ? return YES;

? ? }

?? ?return NO;

}

2.獲取當前的時間

+ (NSString*)getCurrentTimes{

? ? NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

? ? // ----------設置你想要的格式,hh與HH的區(qū)別:分別表示12小時制,24小時制

? ? [formatter setDateFormat:@"YYYY年MM月dd日"];

? ? //現在時間,你可以輸出來看下是什么格式

? ? NSDate *datenow = [NSDate date];

? ? //----------將nsdate按formatter格式轉成nsstring

? ? NSString *currentTimeString = [formatter stringFromDate:datenow];

? ? NSLog(@"currentTimeString =? %@",currentTimeString);

? ? return currentTimeString;

}?

3.手機號碼校驗

+ (BOOL)checkMobilePhoneNumber:(NSString *)phoneNumber {

? ? if (xNullString(phoneNumber)) {

? ? ? ? [self alertViewWithMessage:@"號碼為空" cancelTitle:@"知道了"];

?? ? ? ?return NO;

? ? }

? ? if ([phoneNumber containsString:@"appletest"]) {

? ? ? ? return YES;

? ? }

? ? NSString *regex = @"^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";

? ? NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

? ? BOOL isMatch = [pred evaluateWithObject:phoneNumber];

? ? if (!isMatch) {

? ? ? ? [self alertViewWithMessage:@"請輸入正確的手機號" cancelTitle:@"知道了"];

? ? ? ? return NO;

? ? }

? ? return YES;

}

4.判斷NSString是否為空

#define xNullString(string) ((![string isKindOfClass:[NSString class]]) || [string isEqualToString:@""] || (string == nil) || [string isEqualToString:@""] || [string isKindOfClass:[NSNull class]] || [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0)

5.獲取tabBar ?statusBar 高度

#define xTabBarHeight ([[UIApplication sharedApplication] statusBarFrame].size.height > 20.0f ? 83.0f : 49.0f)

#define xStatusBarHeight ([[UIApplication sharedApplication] statusBarFrame].size.height)

6.判斷是否為iPhoneX

#define IS_iPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO)

7.禁止手機睡眠

[UIApplication?sharedApplication].idleTimerDisabled?=?YES;

8.去除數組中重復的對象

NSArray?*newArr?=?[oldArr?valueForKeyPath:@“@distinctUnionOfObjects.self"];

9.動畫切換window的根控制器

//?options是動畫選項

[UIView?transitionWithView:[UIApplication?sharedApplication].keyWindow?duration:0.5f?options:UIViewAnimationOptionTransitionCrossDissolve?animations:^{

????????BOOL?oldState?=?[UIView?areAnimationsEnabled];

????????[UIView?setAnimationsEnabled:NO];

????????[UIApplication?sharedApplication].keyWindow.rootViewController?=?[RootViewController?new];

????????[UIView?setAnimationsEnabled:oldState];

????}?completion:^(BOOL?finished)?{

????}];

10.設置navigationBar上的title顏色和大小

?[self.navigationController.navigationBar?setTitleTextAttributes:@{NSForegroundColorAttributeName?:?[UIColor?youColor],?NSFontAttributeName?:?[UIFont?systemFontOfSize:15]}]

11.顏色轉圖片

+?(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();

? returnimage;

}

12.由角度轉換弧度,由弧度轉換角度

#define?DegreesToRadian(x)?(M_PI?*?(x)?/?180.0)

#define?RadianToDegrees(radian)?(radian*180.0)/(M_PI)

13.自定義NSLog

#ifdef?DEBUG

#define?NSLog(fmt,?...)?NSLog((@"%s?[Line?%d]?"?fmt),?__PRETTY_FUNCTION__,?__LINE__,?##__VA_ARGS__)

#else

#define?NSLog(...)

#endif

14.修改textField的placeholder的字體顏色、大小

[textField?setValue:[UIColor?redColor]?forKeyPath:@"_placeholderLabel.textColor"];

[textField?setValue:[UIFont?boldSystemFontOfSize:16]?forKeyPath:@"_placeholderLabel.font"];

15.將image保存在相冊中

UIImageWriteToSavedPhotosAlbum(image,?nil,?nil,?nil);

或者

[[PHPhotoLibrary?sharedPhotoLibrary]?performChanges:^{

????????PHAssetChangeRequest?*changeRequest?=?[PHAssetChangeRequest?creationRequestForAssetFromImage:image];

????????changeRequest.creationDate??????????=?[NSDate?date];

????}?completionHandler:^(BOOL?success,?NSError?*error)?{

????????if(success)?{

????????????NSLog(@"successfully?saved");

????????}

????????else{

????????????NSLog(@"error?saving?to?photos:?%@",?error);

? ? ? ?}

????}];

16.獲取視頻的第一幀圖片

?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;

17.移除字符串中的空格和換行

+?(NSString?*)removeSpaceAndNewline:(NSString?*)str?{

????NSString?*temp?=?[str?stringByReplacingOccurrencesOfString:@"?"withString:@""];

????temp?=?[temp?stringByReplacingOccurrencesOfString:@"\r"withString:@""];

????temp?=?[temp?stringByReplacingOccurrencesOfString:@"\n"withString:@""];

????return temp;

}

18.身份證號驗證

-?(BOOL)validateIdentityCard?{

????BOOL?flag;

????if(self.length?<=?0)?{

????????flag?=?NO;

????????returnflag;

????}

????NSString?*regex2?=?@"^(\\d{14}|\\d{17})(\\d|[xX])$";

????NSPredicate?*identityCardPredicate?=?[NSPredicate?predicateWithFormat:@"SELF?MATCHES?%@",regex2];

????return [identityCardPredicate?evaluateWithObject:self];

}

19.image圓角

-?(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();

????returnimage;

}

20.壓縮圖片到指定大小

- (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {

? ? // Compress by quality

? ? CGFloat compression = 1;

? ? NSData *data = UIImageJPEGRepresentation(image, compression);

? ? if (data.length < maxLength) return image;

? ? CGFloat max = 1;

? ? CGFloat min = 0;

? ? for (int i = 0; i < 6; ++i) {

? ? ? ? compression = (max + min) / 2;

? ? ? ? data = UIImageJPEGRepresentation(image, compression);

? ? ? ? if (data.length < maxLength * 0.9) {

? ? ? ? ? ? min = compression;

? ? ? ? } else if (data.length > maxLength) {

? ? ? ? ? ? max = compression;

? ? ? ? } else {

? ? ? ? ? ? break;

? ? ? ? }

? ? }

? ? UIImage *resultImage = [UIImage imageWithData:data];

? ? if (data.length < maxLength) return resultImage;

? ? // Compress by size

? ? NSUInteger lastDataLength = 0;

? ? while (data.length > maxLength && data.length != lastDataLength) {

? ? ? ? lastDataLength = data.length;

? ? ? ? CGFloat ratio = (CGFloat)maxLength / data.length;

? ? ? ? CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank

? ? ? ? UIGraphicsBeginImageContext(size);

? ? ? ? [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];

? ? ? ? resultImage = UIGraphicsGetImageFromCurrentImageContext();

? ? ? ? UIGraphicsEndImageContext();

? ? ? ? data = UIImageJPEGRepresentation(resultImage, compression);

? ? }

? ? return resultImage;

}

21.設置navigationBar上的title顏色和大小

?[self.navigationController.navigationBar?setTitleTextAttributes:@{NSForegroundColorAttributeName?:?[UIColor?youColor],?NSFontAttributeName?:?[UIFont?systemFontOfSize:15]}];

22.獲取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?inenumerator)?{

????????NSString?*path?=?[myCachePath?stringByAppendingPathComponent:fileName];

????????NSDictionary?*fileDict?=?[[NSFileManager?defaultManager]?attributesOfItemAtPath:path?error:nil];

????????count?+=?fileDict.fileSize;//自定義所有緩存大小

????}

????//?得到是字節(jié)??轉化為M

????CGFloat?totalSize?=?((CGFloat)imageCacheSize+count)/1024/1024;

????returntotalSize;

}

23.幾個常用權限判斷

?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(@"沒有相冊權限");

????????}

????}];

24.判斷圖片類型

//通過圖片Data數據第一個字節(jié)?來獲取圖片擴展名

-?(NSString?*)contentTypeForImageData:(NSData?*)data

{

????uint8_t?c;

????[data?getBytes:&c?length:1];

????switch(c)

????{

????????case0xFF:

????????????return @"jpeg";

????????case0x89:

????????????return @"png";

? ? ? ? case0x47:

????????????return @"gif";

? ? ? ? case0x49:

????????case0x4D:

????????????return@"tiff";

? ? ? ? case0x52:

????????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;

}

25.獲取手機和app信息

NSDictionary?*infoDictionary?=?[[NSBundle?mainBundle]?infoDictionary];??

?CFShow(infoDictionary);??

//?app名稱??

?NSString?*app_Name?=?[infoDictionary?objectForKey:@"CFBundleDisplayName"];??

?//?app版本??

?NSString?*app_Version?=?[infoDictionary?objectForKey:@"CFBundleShortVersionString"];??

?//?app?build版本??

?NSString?*app_build?=?[infoDictionary?objectForKey:@"CFBundleVersion"];??

? ? //手機序列號 ?

????NSString*?identifierNumber?=?[[UIDevice?currentDevice]?uniqueIdentifier];??

????NSLog(@"手機序列號:?%@",identifierNumber);??

????//手機別名:?用戶定義的名稱??

????NSString*?userPhoneName?=?[[UIDevice?currentDevice]?name];??

????NSLog(@"手機別名:?%@",?userPhoneName);??

????//設備名稱??

????NSString*?deviceName?=?[[UIDevice?currentDevice]?systemName];??

????NSLog(@"設備名稱:?%@",deviceName?);??

????//手機系統(tǒng)版本??

????NSString*?phoneVersion?=?[[UIDevice?currentDevice]?systemVersion];??

????NSLog(@"手機系統(tǒng)版本:?%@",?phoneVersion);??

????//手機型號??

????NSString*?phoneModel?=?[[UIDevice?currentDevice]?model];??

????NSLog(@"手機型號:?%@",phoneModel?);??

????//地方型號??(國際化區(qū)域名稱)??

????NSString*?localPhoneModel?=?[[UIDevice?currentDevice]?localizedModel];??

????NSLog(@"國際化區(qū)域名稱:?%@",localPhoneModel?);??

? ? NSDictionary?*infoDictionary?=?[[NSBundle?mainBundle]?infoDictionary]; ?

????//?當前應用名稱??

????NSString?*appCurName?=?[infoDictionary?objectForKey:@"CFBundleDisplayName"];??

????NSLog(@"當前應用名稱:%@",appCurName);??

????//?當前應用軟件版本??比如:1.0.1??

????NSString?*appCurVersion?=?[infoDictionary?objectForKey:@"CFBundleShortVersionString"];??

????NSLog(@"當前應用軟件版本:%@",appCurVersion);??

????//?當前應用版本號碼???int類型??

????NSString?*appCurVersionNum?=?[infoDictionary?objectForKey:@"CFBundleVersion"];??

????NSLog(@"當前應用版本號碼:%@",appCurVersionNum);

26.獲取一個類的所有屬性

id?LenderClass?=?objc_getClass("Lender");

unsigned?int?outCount,?i;

objc_property_t?*properties?=?class_copyPropertyList(LenderClass,?&outCount);

for(i?=?0;?i?<?outCount;?i++)?{

????objc_property_t?property?=?properties[i];

????fprintf(stdout,?"%s?%s\n",?property_getName(property),?property_getAttributes(property));

}

27.獲得灰度圖

+?(UIImage*)covertToGrayImageFromImage:(UIImage*)sourceImage

{

????int?width?=?sourceImage.size.width;

????int?height?=?sourceImage.size.height;

????CGColorSpaceRef?colorSpace?=?CGColorSpaceCreateDeviceGray();

????CGContextRef?context?=?CGBitmapContextCreate?(nil,width,height,8,0,colorSpace,kCGImageAlphaNone);

????CGColorSpaceRelease(colorSpace);

????if(context?==?NULL)?{

????????return nil;

????}

????CGContextDrawImage(context,CGRectMake(0,?0,?width,?height),?sourceImage.CGImage);

????CGImageRef?contextRef?=?CGBitmapContextCreateImage(context);

????UIImage?*grayImage?=?[UIImage?imageWithCGImage:contextRef];

????CGContextRelease(context);

????CGImageRelease(contextRef);

????return grayImage;

}

28.為imageView添加倒影

? ? CGRect?frame?=?self.frame;

????frame.origin.y?+=?(frame.size.height?+?1);

? ? UIImageView?*reflectionImageView?=?[[UIImageView?alloc]?initWithFrame:frame];

????self.clipsToBounds?=?TRUE;

????reflectionImageView.contentMode?=?self.contentMode;

????[reflectionImageView?setImage:self.image];

????reflectionImageView.transform?=?CGAffineTransformMakeScale(1.0,?-1.0);

????CALayer?*reflectionLayer?=?[reflectionImageView?layer];

? ? CAGradientLayer?*gradientLayer?=?[CAGradientLayer?layer];

????gradientLayer.bounds?=?reflectionLayer.bounds;

????gradientLayer.position?=?CGPointMake(reflectionLayer.bounds.size.width?/?2,?reflectionLayer.bounds.size.height?*?0.5);

????gradientLayer.colors?=?[NSArray?arrayWithObjects:

????????????????????????????(id)[[UIColor?clearColor]?CGColor],

????????????????????????????(id)[[UIColor?colorWithRed:1.0?green:1.0?blue:1.0?alpha:0.3]?CGColor],?nil];

? ? gradientLayer.startPoint?=?CGPointMake(0.5,0.5);

????gradientLayer.endPoint?=?CGPointMake(0.5,1.0);

????reflectionLayer.mask?=?gradientLayer;

????[self.superview?addSubview:reflectionImageView];

29.畫水印

//?畫水印

-?(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;

}

30.獲取視頻的時長

+?(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);

????returnseconds;

}

31.UILabel設置內邊距

//子類化UILabel,重寫drawTextInRect方法

-?(void)drawTextInRect:(CGRect)rect?{

????//?邊距,上左下右

????UIEdgeInsets?insets?=?{0,?5,?0,?5};

????[superdrawTextInRect:UIEdgeInsetsInsetRect(rect,?insets)];

}

32.UILabel設置文字描邊

//子類化UILabel,重寫drawTextInRect方法

-?(void)drawTextInRect:(CGRect)rect

{

????CGContextRef?c?=?UIGraphicsGetCurrentContext();

????//?設置描邊寬度

????CGContextSetLineWidth(c,?1);

????CGContextSetLineJoin(c,?kCGLineJoinRound);

????CGContextSetTextDrawingMode(c,?kCGTextStroke);

????//?描邊顏色

????self.textColor?=?[UIColor?redColor];

????[superdrawTextInRect:rect];

????//?文本顏色

????self.textColor?=?[UIColor?yellowColor];

????CGContextSetTextDrawingMode(c,?kCGTextFill);

????[superdrawTextInRect:rect];

}

33.壓縮圖片到指定尺寸

- (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize{

? ? // Create a graphics image context

? ? UIGraphicsBeginImageContext(newSize);

? ? // Tell the old image to draw in this new context, with the desired

? ? // new size

? ? [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];

? ? // Get the new image from the context

? ? UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

? ? // End the context

? ? UIGraphicsEndImageContext();

? ? // Return the new image.

? ? return newImage;

}

34.壓縮圖片到指定大小

- (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {

? ? CGFloat compression = 1;

? ? NSData *data = UIImageJPEGRepresentation(image, compression);

? ? if (data.length < maxLength) return image;

? ? CGFloat max = 1;

? ? CGFloat min = 0;

? ? for (int i = 0; i < 6; ++i) {

? ? ? ? compression = (max + min) / 2;

? ? ? ? data = UIImageJPEGRepresentation(image, compression);

? ? ? ? if (data.length < maxLength * 0.9) {

? ? ? ? ? ? min = compression;

? ? ? ? } else if (data.length > maxLength) {

? ? ? ? ? ? max = compression;

? ? ? ? } else {

? ? ? ? ? ? break;

? ? ? ? }

? ? }

? ? UIImage *resultImage = [UIImage imageWithData:data];

? ? if (data.length < maxLength) return resultImage;

? ? NSUInteger lastDataLength = 0;

? ? while (data.length > maxLength && data.length != lastDataLength) {

? ? ? ? lastDataLength = data.length;

? ? ? ? CGFloat ratio = (CGFloat)maxLength / data.length;

? ? ? ? CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank

? ? ? ? UIGraphicsBeginImageContext(size);

? ? ? ? [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];

? ? ? ? resultImage = UIGraphicsGetImageFromCurrentImageContext();

? ? ? ? UIGraphicsEndImageContext();

? ? ? ? data = UIImageJPEGRepresentation(resultImage, compression);

? ? }

? ? return resultImage;

}

34.?獲取 wlan 的 macIP

+ (NSString*)getWLANMacIP {

? ? NSString*ssid =@"Not Found";

? ? NSString*macIp =@"Not Found";

? ? CFArrayRef myArray = CNCopySupportedInterfaces();

? ? if(myArray !=nil) {

? ? ? ? CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));

? ? ? ? if(myDict !=nil) {

? ? ? ? ? ? NSDictionary*dict = (NSDictionary*)CFBridgingRelease(myDict);

? ? ? ? ? ? ssid = [dict valueForKey:@"SSID"];

? ? ? ? ? ? macIp = [dic valueForKey:@"BSSID"];

? ? ? ? } ? ?}

? ? NSLog(@"ssid: %@", ssid);

? ? return ?macIp;

}

35.獲取字符串寬度

+ (CGFloat)getWidthString:(NSString*)wString font:(UIFont*)fFont {

? ? NSDictionary *fontDic = @{NSFontAttributeName:fFont};

? ? CGRect rect = [wString boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 0.0f) options:NSStringDrawingUsesLineFragmentOrigin attributes:fontDic context:nil];

? ? return ?ceilf(rect.size.width);

}

36.?獲取字符串高度

+ (CGFloat)getHeightString:(NSString*)hString font:(UIFont*)font width:(CGFloat)width {

? ? NSDictionary *fontDic = @{NSFontAttributeName : font};

? ? CGRect contentRect = [hString boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:fontDic context:nil];

? ? return ? ceilf(contentRect.size.height);

}

37.改變圖片的透明度

+ (UIImage*)imageByApplyingAlpha:(CGFloat)alpha image:(UIImage*)image {

? ? UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0f);

? ? CGContextRef ctx = UIGraphicsGetCurrentContext();

? ? CGRectarea =CGRectMake(0,0, image.size.width, image.size.height);

? ? CGContextScaleCTM(ctx, 1, -1);

? ? CGContextTranslateCTM(ctx, 0, -area.size.height);

? ? CGContextSetBlendMode(ctx, kCGBlendModeMultiply);

? ? CGContextSetAlpha(ctx, alpha);

? ? CGContextDrawImage(ctx, area, image.CGImage);

? ? UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

? ? UIGraphicsEndImageContext();

? ? return ? newImage;

}

38.獲取手機的運營商

+ (NSString*)operator{

? ? //獲取本機運營商名稱

? ? CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];

? ? CTCarrier *carrier = [info subscriberCellularProvider];

? ? //當前手機所屬運營商名稱

? ? NSString*mobile;

? ? //先判斷有沒有SIM卡,如果沒有則不獲取本機運營商

? ? if(!carrier.isoCountryCode) {

? ? ? ? CLLog(@"沒有SIM卡");

? ? ? ? mobile =@"無運營商";

? ? }else{

? ? ? ? mobile = [carriercarrierName];

? ? }

? ? return mobile;

}

39.震動反饋(iOS10以后)

UIImpactFeedbackGenerator?*feedBackGenertor?=?[[UIImpactFeedbackGenerator?alloc]?initWithStyle:UIImpactFeedbackStyleMedium];

[feedBackGenertor?impactOccurred];

40.震動加音效

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

41.漢語轉拼音

+ (NSString*)getPinYinFromString:(NSString*)string{

CFMutableStringRef aCstring = CFStringCreateMutableCopy(NULL, 0, (__bridge_retained CFStringRef)string);

? ? /**

?? ? *? 創(chuàng)建可變CFString

?? ? *

?? ? *? @paramNULL 使用默認創(chuàng)建器

?? ? *? @param0? ? 長度不限制

?? ? *? @param"張三" cf字串

?? ? *

?? ? *? @return可變字符串

?? ? */

/**

?*? 1. string: 要轉換的字符串(可變的)

?2. range: 要轉換的范圍 NULL全轉換

?3. transform: 指定要怎樣的轉換

?4. reverse: 是否可逆的轉換

?*/

CFStringTransform(aCstring, NULL, kCFStringTransformMandarinLatin, NO);

CFStringTransform(aCstring, NULL, kCFStringTransformStripDiacritics, NO);

NSLog(@"%@",aCstring);

return [NSString stringWithFormat:@"%@",aCstring];

}

42.判斷字符串是否以字母開頭

- (BOOL)isEnglishFirst:(NSString *)str {

? ? NSString *regular = @"^[A-Za-z].+$";

? ? NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regular];


? ? if ([predicate evaluateWithObject:str] == YES){

? ? ? ? return YES;

? ? }else{

? ? ? ? return NO;

? ? }

43.判斷字符串是否以漢字開頭

- (BOOL)isChineseFirst:(NSString *)str {

? ? int utfCode = 0;

? ? void *buffer = &utfCode;

? ? NSRange range = NSMakeRange(0, 1);

? ? BOOL b = [str getBytes:buffer maxLength:2 usedLength:NULL encoding:NSUTF16LittleEndianStringEncoding options:NSStringEncodingConversionExternalRepresentation range:range remainingRange:NULL];

? ? if (b && (utfCode >= 0x4e00 && utfCode <= 0x9fa5)){

? ? ? ? return YES;

? ? }else{

? ? ? ? return NO;

? ? }

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容