iOS小技巧總結,絕對有你想要的(下)


轉載自Cocoa China,原文地址:http://www.cocoachina.com/ios/20170504/19179.html


UIView設置部分圓角

你是不是也遇到過這樣的問題,一個button或者label,只要右邊的兩個角圓角,或者只要一個圓角。該怎麼辦呢。這就需要圖層蒙版來幫助我們了

1
2
3
4
5
6
7
8
CGRect rect = view.bounds;
CGSize radio = CGSizeMake(30, 30); //圓角尺寸
UIRectCorner corner = UIRectCornerTopLeft|UIRectCornerTopRight; //這隻圓角位置
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radio];
CAShapeLayer *masklayer = [[CAShapeLayer alloc]init]; //創建shapelayer
masklayer.frame = view.bounds;
masklayer.path = path.CGPath; //設置路徑
view.layer.mask = masklayer;

取上整與取下整

1
2
3
4
5
6
7
8
9
10
floor(x),有時候也寫做Floor(x),其功能是「下取整」,即取不大於x的最大整數 例如:
x=3.14,floor(x)=3
y=9.99999,floor(y)=9
 
與floor函數對應的是ceil函數,即上取整函數。
 
ceil函數的作用是求不小於給定實數的最小整數。
ceil(2)=ceil(1.2)=cei(1.5)=2.00
 
floor函數與ceil函數的返回值均爲double型

計算字符串字符長度,一個漢字算兩個字符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//方法一:
- (int)convertToInt:(NSString*)strtemp
{
     int strlength = 0;
     char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
     for  (int i=0 ; i([strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++)
     {
         if  (*p)
         {
             p++;
             strlength++;
         }
         else
         {
             p++;
         }
 
     }
     return  strlength;
}
 
//方法二:
-(NSUInteger) unicodeLengthOfString: (NSString *) text
{
     NSUInteger asciiLength = 0;
     for  (NSUInteger i = 0; i ( text.length; i++)
     {
         unichar uc = [text characterAtIndex: i];
         asciiLength += isascii(uc) ? 1 : 2;
     }
     return  asciiLength;
}

給UIView設置圖片

1
2
3
UIImage *image = [UIImage imageNamed:@ "image" ];
self.MYView.layer.contents = (__bridge id _Nullable)(image.CGImage);
self.MYView.layer.contentsRect = CGRectMake(0, 0, 0.5, 0.5);

防止scrollView手勢覆蓋側滑手勢

1
[scrollView.panGestureRecognizerrequireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];

去掉導航欄返回的back標題

[[UIBarButtonItemappearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];

字符串中是否含有中文

1
2
3
4
5
6
7
8
9
10
11
12
+ (BOOL)checkIsChinese:(NSString *)string
{
     for  (int i=0; i(string.length; i++)
     {
         unichar ch = [string characterAtIndex:i];
         if  (0x4E00 (= ch  && ch (= 0x9FA5)
         {
             return  YES;
         }
     }
     return  NO;
}

dispatch_group的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  dispatch_group_t dispatchGroup = dispatch_group_create();
     dispatch_group_enter(dispatchGroup);
     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         NSLog(@ "第一個請求完成" );
         dispatch_group_leave(dispatchGroup);
     });
 
     dispatch_group_enter(dispatchGroup);
 
     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         NSLog(@ "第二個請求完成" );
         dispatch_group_leave(dispatchGroup);
     });
 
     dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
         NSLog(@ "請求完成" );
     });

UITextField每四位加一個空格,實現代理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
     // 四位加一個空格
     if  ([string isEqualToString:@ "" ])
     {
         // 刪除字符
         if  ((textField.text.length - 2) % 5 == 0)
         {
             textField.text = [textField.text substringToIndex:textField.text.length - 1];
         }
         return  YES;
     }
     else
     {
         if  (textField.text.length % 5 == 0)
         {
             textField.text = [NSString stringWithFormat:@ "%@ " , textField.text];
         }
     }
     return  YES;
}

獲取私有屬性和成員變量 #import(objc/runtime.h)(由於系統原因此處用圓括號代替尖括號)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//獲取私有屬性 比如設置UIDatePicker的字體顏色
- (void)setTextColor
{
     //獲取所有的屬性,去查看有沒有對應的屬性
     unsigned int count = 0;
     objc_property_t *propertys = class_copyPropertyList([UIDatePicker class], &count);
     for (int i = 0;i ( count;i ++)
     {
         //獲得每一個屬性
         objc_property_t property = propertys[i];
         //獲得屬性對應的nsstring
         NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
         //輸出打印看對應的屬性
         NSLog(@ "propertyname = %@" ,propertyName);
         if  ([propertyName isEqualToString:@ "textColor" ])
         {
             [datePicker setValue:[UIColor whiteColor] forKey:propertyName];
         }
     }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//獲得成員變量 比如修改UIAlertAction的按鈕字體顏色
     unsigned int count = 0;
     Ivar *ivars = class_copyIvarList([UIAlertAction class], &count);
     for (int i =0;i ( count;i ++)
     {
         Ivar ivar = ivars[i];
         NSString *ivarName = [NSString stringWithCString:ivar_getName(ivar) encoding:NSUTF8StringEncoding];
         NSLog(@ "uialertion.ivarName = %@" ,ivarName);
         if  ([ivarName isEqualToString:@ "_titleTextColor" ])
         {
             [alertOk setValue:[UIColor blueColor] forKey:@ "titleTextColor" ];
             [alertCancel setValue:[UIColor purpleColor] forKey:@ "titleTextColor" ];
         }
     }

獲取手機安裝的應用

1
2
3
4
5
6
7
8
9
10
Class c =NSClassFromString(@ "LSApplicationWorkspace" );
id s = [(id)c performSelector:NSSelectorFromString(@ "defaultWorkspace" )];
NSArray *array = [s performSelector:NSSelectorFromString(@ "allInstalledApplications" )];
for  (id item  in  array)
{
     NSLog(@ "%@" ,[item performSelector:NSSelectorFromString(@ "applicationIdentifier" )]);
     //NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleIdentifier")]);
     NSLog(@ "%@" ,[item performSelector:NSSelectorFromString(@ "bundleVersion" )]);
     NSLog(@ "%@" ,[item performSelector:NSSelectorFromString(@ "shortVersionString" )]);
}

判斷兩個日期是否在同一周 寫在NSDate的category裏面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (BOOL)isSameDateWithDate:(NSDate *)date
{
     //日期間隔大於七天之間返回NO
     if  (fabs([self timeIntervalSinceDate:date]) >= 7 * 24 *3600)
     {
         return  NO;
     }
 
     NSCalendar *calender = [NSCalendar currentCalendar];
     calender.firstWeekday = 2; //設置每週第一天從週一開始
     //計算兩個日期分別爲這年第幾周
     NSUInteger countSelf = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:self];
     NSUInteger countDate = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:date];
 
     //相等就在同一周,不相等就不在同一周
     return  countSelf == countDate;
}

應用內打開系統設置界面

1
2
3
//iOS8之後
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
//如果App沒有添加權限,顯示的是設定界面。如果App有添加權限(例如通知),顯示的是App的設定界面。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//iOS8之前
//先添加一個url type如下圖,在代碼中調用如下代碼,即可跳轉到設置頁面的對應項
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@ "prefs:root=WIFI" ]];
 
可選值如下:
About — prefs:root=General&path=About
Accessibility — prefs:root=General&path=ACCESSIBILITY
Airplane Mode On — prefs:root=AIRPLANE_MODE
Auto-Lock — prefs:root=General&path=AUTOLOCK
Brightness — prefs:root=Brightness
Bluetooth — prefs:root=General&path=Bluetooth
Date & Time — prefs:root=General&path=DATE_AND_TIME
FaceTime — prefs:root=FACETIME
General — prefs:root=General
Keyboard — prefs:root=General&path=Keyboard
iCloud — prefs:root=CASTLE
iCloud Storage & Backup — prefs:root=CASTLE&path=STORAGE_AND_BACKUP
International — prefs:root=General&path=INTERNATIONAL
Location Services — prefs:root=LOCATION_SERVICES
Music — prefs:root=MUSIC
Music Equalizer — prefs:root=MUSIC&path=EQ
Music Volume Limit — prefs:root=MUSIC&path=VolumeLimit
Network — prefs:root=General&path=Network
Nike + iPod — prefs:root=NIKE_PLUS_IPOD
Notes — prefs:root=NOTES
Notification — prefs:root=NOTIFICATI*****_ID
Phone — prefs:root=Phone
Photos — prefs:root=Photos
Profile — prefs:root=General&path=ManagedConfigurationList
Reset — prefs:root=General&path=Reset
Safari — prefs:root=Safari
Siri — prefs:root=General&path=Assistant
Sounds — prefs:root=Sounds
Software Update — prefs:root=General&path=SOFTWARE_UPDATE_LINK
Store — prefs:root=STORE
Twitter — prefs:root=TWITTER
Usage — prefs:root=General&path=USAGE
v*n — prefs:root=General&path=Network/v*n
Wallpaper — prefs:root=Wallpaper
Wi-Fi — prefs:root=WIFI

1608265-0336b1d206210cf1.png

屏蔽觸發事件,2秒後取消屏蔽

1
2
3
4
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
     [[UIApplication sharedApplication] endIgnoringInteractionEvents]
});

動畫暫停再開始

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-(void)pauseLayer:(CALayer *)layer
{
     CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
     layer.speed = 0.0;
     layer.timeOffset = pausedTime;
}
 
-(void)resumeLayer:(CALayer *)layer
{
     CFTimeInterval pausedTime = [layer timeOffset];
     layer.speed = 1.0;
     layer.timeOffset = 0.0;
     layer.beginTime = 0.0;
     CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
     layer.beginTime = timeSincePause;
}

fillRule原理

1608265-102c8b228637e659.png

iOS中數字的格式化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//通過NSNumberFormatter,同樣可以設置NSNumber輸出的格式。例如如下代碼:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:[NSNumber numberWithInt:123456789]];
NSLog(@ "Formatted number string:%@" ,string);
//輸出結果爲:[1223:403] Formatted number string:123,456,789
 
//其中NSNumberFormatter類有個屬性numberStyle,它是一個枚舉型,設置不同的值可以輸出不同的數字格式。該枚舉包括:
typedef NS_ENUM(NSUInteger, NSNumberFormatterStyle) {
     NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle,
     NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle,
     NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle,
     NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle,
     NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle,
     NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle
};
//各個枚舉對應輸出數字格式的效果如下:其中第三項和最後一項的輸出會根據系統設置的語言區域的不同而不同。
[1243:403] Formatted number string:123456789
[1243:403] Formatted number string:123,456,789
[1243:403] Formatted number string:¥123,456,789.00
[1243:403] Formatted number string:-539,222,988%
[1243:403] Formatted number string:1.23456789E8
[1243:403] Formatted number string:一億二千三百四十五萬六千七百八十九

如何獲取WebView所有的圖片地址

在網頁加載完成時,通過js獲取圖片和添加點擊的識別方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//UIWebView
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
     //這裏是js,主要目的實現對url的獲取
     static  NSString * const jsGetImages =
     @" function  getImages(){\
     var  objs = document.getElementsByTagName(\"img\");\
     var  imgScr =  '' ;\
     for ( var  i=0;i(objs.length;i++){\
     imgScr = imgScr + objs[i].src +  '+' ;\
     };\
     return  imgScr;\
     };";
 
     [webView stringByEvaluatingJavaScriptFromString:jsGetImages]; //注入js方法
     NSString *urlResult = [webView stringByEvaluatingJavaScriptFromString:@ "getImages()" ];
     NSArray *urlArray = [NSMutableArray arrayWithArray:[urlResult componentsSeparatedByString:@ "+" ]];
     //urlResurlt 就是獲取到得所有圖片的url的拼接;mUrlArray就是所有Url的數組
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//WKWebView
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
     static  NSString * const jsGetImages =
     @" function  getImages(){\
     var  objs = document.getElementsByTagName(\"img\");\
     var  imgScr =  '' ;\
     for ( var  i=0;i(objs.length;i++){\
     imgScr = imgScr + objs[i].src +  '+' ;\
     };\
     return  imgScr;\
     };";
 
     [webView evaluateJavaScript:jsGetImages completionHandler:nil];
     [webView evaluateJavaScript:@ "getImages()"  completionHandler:^(id _Nullable result, NSError * _Nullable error) {
         NSLog(@ "%@" ,result);
     }];
}

獲取到webview的高度

1
CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@ "document.body.offsetHeight" ] floatValue];

navigationBar變爲純透明

1
2
3
4
5
6
7
8
//第一種方法
//導航欄純透明
[self.navigationBar setBackgroundImage:[UIImage  new ] forBarMetrics:UIBarMetricsDefault];
//去掉導航欄底部的黑線
self.navigationBar.shadowImage = [UIImage  new ];
 
//第二種方法
[[self.navigationBar subviews] objectAtIndex:0].alpha = 0;

tabBar同理

1
2
[self.tabBar setBackgroundImage:[UIImage  new ]];
self.tabBar.shadowImage = [UIImage  new ];

navigationBar根據滑動距離的漸變色實現

1
2
3
4
5
6
7
//第一種
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
     CGFloat offsetToShow = 200.0; //滑動多少就完全顯示
     CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow;
     [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = alpha;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//第二種
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
     CGFloat offsetToShow = 200.0;
     CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow;
 
     [self.navigationController.navigationBar setShadowImage:[UIImage  new ]];
     [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor orangeColor]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];
}
 
//生成一張純色的圖片
- (UIImage *)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 *theImage = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
 
     return  theImage;
}

iOS 開發中一些相關的路徑

1
2
3
4
5
6
7
8
9
10
11
模擬器的位置:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs 
文檔安裝位置:
/Applications/Xcode.app/Contents/Developer/Documentation/DocSets
插件保存路徑:
~/Library/ApplicationSupport/Developer/Shared/Xcode/Plug-ins
自定義代碼段的保存路徑:
~/Library/Developer/Xcode/UserData/CodeSnippets/ 
如果找不到CodeSnippets文件夾,可以自己新建一個CodeSnippets文件夾。
描述文件路徑
~/Library/MobileDevice/Provisioning Profiles

navigationItem的BarButtonItem如何緊靠屏幕右邊界或者左邊界?

一般情況下,右邊的item會和屏幕右側保持一段距離:

1608265-2b25556ad97436ad.png

下面是通過添加一個負值寬度的固定間距的item來解決,也可以改變寬度實現不同的間隔:

1
2
3
4
5
6
7
8
UIImage *img = [[UIImage imageNamed:@ "icon_cog" ] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//寬度爲負數的固定間距的系統item
UIBarButtonItem *rightNegativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
[rightNegativeSpacer setWidth:-15];
 
UIBarButtonItem *rightBtnItem1 = [[UIBarButtonItem alloc]initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonItemClicked:)];
UIBarButtonItem *rightBtnItem2 = [[UIBarButtonItem alloc]initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonItemClicked:)];
self.navigationItem.rightBarButtonItems = @[rightNegativeSpacer,rightBtnItem1,rightBtnItem2];

1608265-649770861a945c45.png

NSString進行URL編碼和解碼

1
2
3
4
5
6
7
NSString *string = @ "http://abc.com?aaa=你好&bbb=tttee" ;
 
string = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
 
//解碼 打印:http://abc.com?aaa=你好&bbb=tttee
string = [string stringByRemovingPercentEncoding];

UIWebView設置User-Agent。

1
2
3
4
5
//設置
NSDictionary *dic = @{@ "UserAgent" :@ "your UserAgent" };
[[NSUserDefaults standardUserDefaults] registerDefaults:dic];
//獲取
NSString *agent = [self.WebView stringByEvaluatingJavaScriptFromString:@ "navigator.userAgent" ];

獲取硬盤總容量與可用容量:

1
2
3
4
5
NSFileManager *fileManager = [NSFileManager defaultManager];
NSDictionary *attributes = [fileManager attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
1
NSLog(@ "容量%.2fG" ,[attributes[NSFileSystemSize] doubleValue] / (powf(1024, 3)));
NSLog(@ "可用%.2fG" ,[attributes[NSFileSystemFreeSize] doubleValue] / powf(1024, 3));

獲取UIColor的RGBA值

1
2
3
4
5
6
UIColor *color = [UIColor colorWithRed:0.2 green:0.3 blue:0.9 alpha:1.0];
const CGFloat *components = CGColorGetComponents(color.CGColor);
NSLog(@ "Red: %.1f" , components[0]);
NSLog(@ "Green: %.1f" , components[1]);
NSLog(@ "Blue: %.1f" , components[2]);
NSLog(@ "Alpha: %.1f" , components[3]);

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

1
2
[self.textField setValue:[UIColor redColor] forKeyPath:@ "_placeholderLabel.textColor" ];
[self.textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@ "_placeholderLabel.font" ];

AFN移除JSON中的NSNull

1
2
AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
response.removesKeysWithNullValues = YES;

ceil()和floor()

ceil()功 能:返回大於或者等於指定表達式的最小整數

floor()功 能:返回小於或者等於指定表達式的最大整數

UIWebView裏面的圖片自適應屏幕

在webView加載完的代理方法裏面這樣寫:

相關文章
相關標籤/搜索