前言:
以下內(nèi)容是作者在實際開發(fā)中所總結(jié)的希柿,主要列舉了一些實用小技巧阐肤,也希望在實際開發(fā)中能夠幫到你缴罗。
- 設置控件的圓角:
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 = @"數(shù)不清的漫山花朵"\\
"給這座大山添加了不少情趣";
NSLog(@"%@",str);
- 判斷一個字符串中是否包含另外一個字符串:
NSString *str1 = @"abcqwqwq";
NSString *str2 = @"abc";
NSLog(@"%@", [str1 rangeOfString:str2].length != 0 ? @"包含" : @"不包含");
- 獲取plist文件的數(shù)據(jù):
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));
}
- 系統(tǒng)偏好存儲的方式:
//1. NSUserDefaults簡單實用:
// 創(chuàng)建偏好對象
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字符串轉(zhuǎn)換成C字符:
sql.UTF8String
- 結(jié)構(gòu)體循環(huán):
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"第 %d 項內(nèi)容是 %@", (int)idx, obj);
if ([@"王五" isEqualToString:obj]) *stop = YES;
}];
- 不使用HTTPS方法:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
- 隨機數(shù):
int x = arc4random() % 100;
//生成指定范圍隨機數(shù)[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];
//設置翻轉(zhuǎn)方向
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
//動畫結(jié)束
[UIView commitAnimations];
- arc和非arc的轉(zhuǎn)換:
如果你的項目使用的非 ARC 模式肥惭,則為 ARC 模式的代碼文件加入 -fobjc-arc 標簽么伯。
如果你的項目使用的是 ARC 模式疟暖,則為非 ARC 模式的代碼文件加入 -fno-objc-arc 標簽。
- Json(反序列化):
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
- URL中有特殊字符需要加百分號轉(zhuǎn)譯:
NSLog(@"%@",[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]);
// 取反
NSLog(@"%@",[str stringByRemovingPercentEncoding]);
- 局部刷新:
// 刷新指定行
NSIndexPath *path = [NSIndexPath indexPathForRow:alertView.tag inSection:0];
[self.tableview reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationRight];
//如果不進行刷新會怎么樣田柔?(修改之后不會即時刷新俐巴,要等到重新對cell進行數(shù)據(jù)填充的時候才會刷新)
- 屏幕自動旋轉(zhuǎn):
self.imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
- 獲取系統(tǒng)版本:
[[UIDevice currentDevice].systemVersion doubleValue];
- 設置狀態(tài)背景色:
// 第一種方式:
在info.plist文件中添加View controller-based status bar appearance 設為 NO
在AppDelegate.m 文件中的didFinishLaunchingWithOptionsfa方法中添加application.statusBarStyle = UIStatusBarStyleLightContent; 即可改變狀態(tài)欄背景色。
總結(jié):這種方法在ios9之前不會報錯凯楔,但ios9后會報錯窜骄,但不影響程序的正常運行,這是蘋果自身的bug摆屯。
//第二種方式:在重寫的UINavigationController控制器中添加一下代碼
-(UIStatusBarStyle)preferredStatusBarStyle {
return UIStatusBarStyleLightContent;
}
總結(jié):暫時能夠解決問題邻遏,但目前不知解決的思路。
- 視圖位置交換:
//把一個子視圖放到最下面
[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控制其中子控制器的個數(shù):
self.viewControllers.count;
- 字體設置:
attr[NSForegroundColorAttributeName ] = [UIColor whiteColor];
attr[NSFontAttributeName] = [UIFont systemFontOfSize:20];
[navBar setTitleTextAttributes:attr];
- 隱藏tabbar:
viewController.hidesBottomBarWhenPushed = YES;
- 禁用系統(tǒng)自帶側(cè)滑:
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"];
- 返回不帶狀態(tài)欄的Rect:
CGRect bounds = [[UIScreen mainScreen] applicationFrame];
- iOS各種機型的屏幕適配問題以iPhone6P為基準:
#define SYRealValue(value) ((value)/414.0f*[UIScreen mainScreen].bounds.size.width)
- 數(shù)組轉(zhuǎn)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 轉(zhuǎn) NSArray :
NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:[result dataUsingEncoding:NSUTF8StringEncoding];
options:0 error:NULL];
- 修改cell選中狀態(tài)的背景:
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); // 旋轉(zhuǎn)
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 切換目錄到需要轉(zhuǎn)換的.m文件目錄下夭坪,輸入以下命令:
clang -rewrite-objc fileName.m
- 獲取當前界面的View:
UIView *view = [[UIApplication sharedApplication].windows lastObject];
- 如何從A應用跳轉(zhuǎn)到B應用::
//1.簡單的跳轉(zhuǎn):
第一步:在B應用中配置URL Schemes
第二步:配置A應用訪問B應用的NSURL *url = [NSURL URLWithString:@"weixin://"]; weixin就是B應用中配置URL Schemes參數(shù)。
第三步:在A應用中通過[[UIApplication sharedApplication] canOpenURL:url] 判斷應用是否存在过椎。
第四步:如果應用存在打開應用[[UIApplication sharedApplication] openURL:url];
備注:在執(zhí)行第三步操作時室梅,控制臺可能打印錯誤信息,原因是蘋果公司為了提高應用的安全性疚宇,想要訪問必須設置對應白名單亡鼠,白名單中最大允許50個應用被訪問,如何設置白名單敷待,
進入Info.plist文件中增加以下代碼:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>weixin</string>
.....
</array>
// 2 .跳轉(zhuǎn)傳參數(shù):
在簡單的跳轉(zhuǎn)的url中稍作修改:
URL配置:
NSURL *url = [NSURL URLWithString:@"weixin://www.shixueqian.com/abc?title=hello&content=helloworld"]; //打開url
在B應用的AppDelegate.m 文件中增加接收參數(shù)的代理就行:
-(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 ; //回調(diào)是在iOS2.0的時候推出的间涵,參數(shù)只有url。
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation ;//B回到是在iOS4.2的時候推出的榜揖,參數(shù)有url sourceApplication annotation
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options NS_AVAILABLE_IOS(9_0);//B回到是在iOS4.2的時候推出的浑厚,參數(shù)有url sourceApplication annotation
- 通過運行時股耽,置換兩個方法執(zhí)行順序:
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
- 數(shù)組去重的三個小技巧:
+(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) {
// // 檢查數(shù)組中是否包含該值
// 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轉(zhuǎn)NSDate:
// 字符轉(zhuǎn)日期 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];
}
- 打印系統(tǒng)所有已注冊的字體名稱:
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跳轉(zhuǎn)到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];
//將漢字轉(zhuǎn)換為拼音(帶音標)
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
NSLog(@"%@", pinyin);
//去掉拼音的音標
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
NSLog(@"%@", pinyin);
//返回最近結(jié)果
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位數(shù)表示震嫉,如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顏色轉(zhuǎn)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]
總結(jié):
文章后續(xù)還會更新担败。文章中可能存在錯別字或者理解不到位的地方昔穴,歡迎挑刺,如果你也是一枚IOS愛好者提前,請加入我們的QQ群:126440594吗货,一起分享,一起成長岖研。