iOS 開發(fā)中一些技巧歸納

通過自己開發(fā)以及借鑒的別人的經(jīng)驗,總結一下一些開發(fā)中經(jīng)常用到的技巧知識點,也算是做個小筆記吧。

1、控件的局部圓角問題

CGRect rect = CGRectMake(0, 0, 100, 50);

CGSize radio = CGSizeMake(5, 5);//圓角尺寸

UIRectCorner corner = UIRectCornerTopLeft|UIRectCornerTopRight;//這只圓角位置

UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radio];

CAShapeLayer *masklayer = [[CAShapeLayer alloc]init];//創(chuàng)建shapelayer

masklayer.frame = button.bounds;

masklayer.path = path.CGPath;//設置路徑

button.layer.mask = masklayer;

舉例為button,其它繼承自UIView的控件都可以

//指定了需要成為圓角的角。該參數(shù)是UIRectCorner類型的,可選的值有:

* UIRectCornerTopLeft

* UIRectCornerTopRight

* UIRectCornerBottomLeft

* UIRectCornerBottomRight

* UIRectCornerAllCorners

從名字很容易看出來代表的意思,使用“|”來組合就好了。

設置滑動的時候隱藏navigationBar2、navigationBar的透明問題

如果僅僅把navigationBar的alpha設為0的話,那就相當于把navigationBar給隱藏了,大家都知道,父視圖的alpha設置為0的話,那么子視圖全都會透明的。那么相應的navigationBar的標題和左右兩個按鈕都會消失。這樣顯然達不到我們要求的效果。

(1)如果僅僅是想要navigationBar透明,按鈕和標題都在可以使用以下方法:

[self.navigationController.navigationBar setBackgroundImage:[UIImage new]

forBarMetrics:UIBarMetricsDefault];//給navigationBar設置一個空的背景圖片即可實現(xiàn)透明,而且標題按鈕都在

細心的你會發(fā)現(xiàn)上面有一條線如下圖:

self.navigationController.navigationBar.shadowImage = [UIImage new];//其實這個線也是image控制的。設為空即可

2)如果你想在透明的基礎上實現(xiàn)根據(jù)下拉距離,由透明變得不透明的效果,那么上面那個就顯得力不從心了,這就需要我們采用另外一種方法了

//navigationBar是一個復合視圖,它是有許多個控件組成的,那么我們就可以從他的內(nèi)部入手[[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = 0;//這里可以根據(jù)scrollView的偏移量來設置alpha就實現(xiàn)了漸變透明的效果

3、全局設置navigationBar標題的樣式和barItem的標題樣式

//UIColorWithHexRGB( )這個方法是自己定義的,這里只需要給個顏色就好了

[[UINavigationBar appearance] setBarTintColor:UIColorWithHexRGB(0xfefefe)];[[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:UIColorWithHexRGB(0xfe6d27)}];

[[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:10],NSForegroundColorAttributeName : UIColorWithHexRGB(0x666666)} forState:UIControlStateNormal];

[[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSiz]]

4、navigationBar隱藏顯示的過度

一個頁面隱藏navigationBar,另一個不隱藏。兩個頁面進行push和pop的時候,尤其是有側滑手勢返回的時候,不做處理就會造成滑動返回時,navigationBar位置是空的,直接顯示一個黑色或者顯示下面一層視圖,很難看。這就需要我們加入過度動畫來隱藏或顯示navigationBar:

在返回后將要出現(xiàn)的頁面實現(xiàn)viewWillAppear方法,需要隱藏就設為YES,需要顯示就設為NO

- (void)viewWillAppear:(BOOL)animated{

[super viewWillAppear:animated];

[self.navigationController setNavigationBarHidden:NO animated:YES];

}

5、給webView添加頭視圖

webView是一個復合視圖,里面包含有一個scrollView,scrollView里面是一個UIWebBrowserView(負責顯示W(wǎng)ebView的內(nèi)容)

UIView *webBrowserView = self.webView.scrollView.subviews[0];//拿到webView的webBrowserView

self.backHeadImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth*2/3.0)];

[_backHeadImageView sd_setImageWithURL:[NSURL URLWithString:self.imageUrl] placeholderImage:[UIImage imageNamed:@"placeholderImage"]];

[self.webView insertSubview:_backHeadImageView belowSubview:self.webView.scrollView];

//把backHeadImageView插入到webView的scrollView下面

CGRect frame = self.webBrowserView.frame;

frame.origin.y = CGRectGetMaxY(_backHeadImageView.frame);

self.webBrowserView.frame = frame;

//更改webBrowserView的frame向下移backHeadImageView的高度,使其可見

6、模態(tài)跳轉的動畫設置

設置模態(tài)跳轉的動畫,系統(tǒng)提供了四種可供選擇

DetailViewController *detailVC = [[DetailViewController alloc]init];

//UIModalTransitionStyleFlipHorizontal 翻轉

//UIModalTransitionStyleCoverVertical 底部滑出

//UIModalTransitionStyleCrossDissolve 漸顯

//UIModalTransitionStylePartialCurl 翻頁

detailVC.modalTransitionStyle = UIModalTransitionStylePartialCurl;

[self presentViewController:detailVC animated:YES completion:nil];

7、圖片處理只拿到圖片的一部分

UIImage *image = [UIImage imageNamed:filename];

CGImageRef imageRef = image.CGImage;

CGRect rect = CGRectMake(origin.x, origin.y ,size.width, size.height);

//這里的寬高是相對于圖片的真實大小

//比如你的圖片是400x400的那么(0,0,400,400)就是圖片的全尺寸,想取哪一部分就設置相應坐標即可

CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, rect);

UIImage *imageRect = [[UIImage alloc] initWithCGImage:imageRefRect];

8、調用代碼使APP進入后臺,達到點擊Home鍵的效果

[[UIApplication sharedApplication] performSelector:@selector(suspend)];

suspend的英文意思有:暫停; 懸; 掛; 延緩;

9、獲取UIWebView的高度

- (void)webViewDidFinishLoad:(UIWebView *)webView? {

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

CGRect frame = webView.frame;

webView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height);

}

10、去掉UITableView多余的分割線

tableView.tableFooterView = [UIView new];

11、調整cell分割線的位置,兩個方法一起用

-(void)viewDidLayoutSubviews {

if ([self.mytableview respondsToSelector:@selector(setSeparatorInset:)]) {

[self.mytableview setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

}

if ([self.mytableview respondsToSelector:@selector(setLayoutMargins:)])? {

[self.mytableview setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];

}

}

#pragma mark - cell分割線

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

{

if ([cell respondsToSelector:@selector(setSeparatorInset:)]){

[cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

}

if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {

[cell setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];

}

}

12、UISearchController和UISearchBar的Cancle按鈕改title問題,簡單粗暴

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{

searchController.searchBar.showsCancelButton = YES;

UIButton *canceLBtn = [searchController.searchBar valueForKey:@"cancelButton"];

[canceLBtn setTitle:@"取消" forState:UIControlStateNormal];

[canceLBtn setTitleColor:[UIColor colorWithRed:14.0/255.0 green:180.0/255.0 blue:0.0/255.0 alpha:1.00] forState:UIControlStateNormal];

searchBar.showsCancelButton = YES;

return YES;

}

13、UITableView收起鍵盤何必這么麻煩

一個屬性搞定,效果好(UIScrollView同樣可以使用)

以前是不是覺得[self.view endEditing:YES];很屌,這個下面的更屌。

yourTableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

另外一個枚舉為UIScrollViewKeyboardDismissModeInteractive,表示在鍵盤內(nèi)部滑動,鍵盤逐漸下去。

14、NSTimer

1、NSTimer計算的時間并不精確

2、NSTimer需要添加到runLoop運行才會執(zhí)行,但是這個runLoop的線程必須是已經(jīng)開啟。

3、NSTimer會對它的tagert進行retain,我們必須對其重復性的使用intvailte停止。target如果是self(指UIViewController),那么VC的retainCount+1,如果你不釋放NSTimer,那么你的VC就不會dealloc了,內(nèi)存泄漏了。

15、用十六進制獲取UIColor(類方法或者Category都可以,這里我用工具類方法)

+ (UIColor *)colorWithHexString:(NSString *)color

{

NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

// String should be 6 or 8 characters

if ([cString length] < 6) {

return [UIColor clearColor];

}

// strip 0X if it appears

if ([cString hasPrefix:@"0X"])

cString = [cString substringFromIndex:2];

if ([cString hasPrefix:@"#"])

cString = [cString substringFromIndex:1];

if ([cString length] != 6)

return [UIColor clearColor];

// Separate into r, g, b substrings

NSRange range;

range.location = 0;

range.length = 2;

//r

NSString *rString = [cString substringWithRange:range];

//g

range.location = 2;

NSString *gString = [cString substringWithRange:range];

//b

range.location = 4;

NSString *bString = [cString substringWithRange:range];

// Scan values

unsigned int r, g, b;

[[NSScanner scannerWithString:rString] scanHexInt:&r];

[[NSScanner scannerWithString:gString] scanHexInt:&g];

[[NSScanner scannerWithString:bString] scanHexInt:&b];

return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];

}

16、獲取今天是星期幾

+ (NSString *) getweekDayStringWithDate:(NSDate *) date

{

NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; // 指定日歷的算法

NSDateComponents *comps = [calendar components:NSWeekdayCalendarUnit fromDate:date];

// 1 是周日,2是周一 3.以此類推

NSNumber * weekNumber = @([comps weekday]);

NSInteger weekInt = [weekNumber integerValue];

NSString *weekDayString = @"(周一)";

switch (weekInt) {

case 1:

{

weekDayString = @"(周日)";

}

break;

case 2:

{

weekDayString = @"(周一)";

}

break;

case 3:

{

weekDayString = @"(周二)";

}

break;

case 4:

{

weekDayString = @"(周三)";

}

break;

case 5:

{

weekDayString = @"(周四)";

}

break;

case 6:

{

weekDayString = @"(周五)";

}

break;

case 7:

{

weekDayString = @"(周六)";

}

break;

default:

break;

}

return weekDayString;

}

17、設置滑動的時候隱藏navigationBar

navigationController.hidesBarsOnSwipe = Yes;

18、iOS畫虛線

記得先 QuartzCore框架的導入#importCGContextRef context =UIGraphicsGetCurrentContext();

CGContextBeginPath(context);

CGContextSetLineWidth(context, 2.0);

CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);

CGFloat lengths[] = {10,10};

CGContextSetLineDash(context, 0, lengths,2);

CGContextMoveToPoint(context, 10.0, 20.0);

CGContextAddLineToPoint(context, 310.0,20.0);

CGContextStrokePath(context);

CGContextClosePath(context);

19、自動布局中多行UILabel,需要設置其preferredMaxLayoutWidth屬性才能正常顯示多行內(nèi)容。另外如果出現(xiàn)顯示不全文本,可以在計算的結果基礎上+0.5。

CGFloat h = [model.message boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - kGAP-kAvatar_Size - 2*kGAP, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.height+0.5;

20、禁止程序運行時自動鎖屏

[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

21、KVC相關,支持操作符

KVC同時還提供了很復雜的函數(shù),主要有下面這些

①簡單集合運算符

簡單集合運算符共有@avg, @count , @max , @min ,@sum5種,都表示啥不用我說了吧, 目前還不支持自定義

@interface Book : NSObject

@property (nonatomic,copy)? NSString* name;

@property (nonatomic,assign)? CGFloat price;

@end

@implementation Book

@end

Book *book1 = [Book new];

book1.name = @"The Great Gastby";

book1.price = 22;

Book *book2 = [Book new];

book2.name = @"Time History";

book2.price = 12;

Book *book3 = [Book new];

book3.name = @"Wrong Hole";

book3.price = 111;

Book *book4 = [Book new];

book4.name = @"Wrong Hole";

book4.price = 111;

NSArray* arrBooks = @[book1,book2,book3,book4];

NSNumber* sum = [arrBooks valueForKeyPath:@"@sum.price"];

NSLog(@"sum:%f",sum.floatValue);

NSNumber* avg = [arrBooks valueForKeyPath:@"@avg.price"];

NSLog(@"avg:%f",avg.floatValue);

NSNumber* count = [arrBooks valueForKeyPath:@"@count"];

NSLog(@"count:%f",count.floatValue);

NSNumber* min = [arrBooks valueForKeyPath:@"@min.price"];

NSLog(@"min:%f",min.floatValue);

NSNumber* max = [arrBooks valueForKeyPath:@"@max.price"];

NSLog(@"max:%f",max.floatValue);

打印結果

2016-04-20 16:45:54.696 KVCDemo[1484:127089] sum:256.000000

2016-04-20 16:45:54.697 KVCDemo[1484:127089] avg:64.000000

2016-04-20 16:45:54.697 KVCDemo[1484:127089] count:4.000000

2016-04-20 16:45:54.697 KVCDemo[1484:127089] min:12.000000

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

22、強制讓App直接退出(非閃退,非崩潰)

- (void)exitApplication {

AppDelegate *app = [UIApplication sharedApplication].delegate;

UIWindow *window = app.window;

[UIView animateWithDuration:1.0f animations:^{

window.alpha = 0;

} completion:^(BOOL finished) {

exit(0);

}];

}

23、Label行間距

NSMutableAttributedString *attributedString =

[[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];

NSMutableParagraphStyle *paragraphStyle =? [[NSMutableParagraphStyle alloc] init];

[paragraphStyle setLineSpacing:3];

//調整行間距

[attributedString addAttribute:NSParagraphStyleAttributeName

value:paragraphStyle

range:NSMakeRange(0, [self.contentLabel.text length])];

self.contentLabel.attributedText = attributedString;

24、MRC和ARC混編設置方式

在XCode中targets的build phases選項下Compile Sources下選擇 不需要arc編譯的文件

雙擊輸入 -fno-objc-arc 即可

MRC工程中也可以使用ARC的類,方法如下:

在XCode中targets的build phases選項下Compile Sources下選擇要使用arc編譯的文件

雙擊輸入 -fobjc-arc 即可

25、把tableview里cell的小對勾的顏色改成別的顏色

tableView.tintColor = [UIColor redColor];

26、解決同時按兩個按鈕進兩個view的問題

[button setExclusiveTouch:YES];

27、修改textFieldplaceholder字體顏色和大小

textField.placeholder = @"請輸入用戶名";

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

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

28、禁止textField和textView的復制粘貼菜單

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender

{

if ([UIMenuController sharedMenuController]) {

[UIMenuController sharedMenuController].menuVisible = NO;

}

return NO;

}

29、二級三級頁面隱藏系統(tǒng)tabbar

1、單個處理

YourViewController *yourVC = [YourViewController new];

yourVC.hidesBottomBarWhenPushed = YES;

[self.navigationController pushViewController:yourVC animated:YES];

2.統(tǒng)一在基類里面處理

新建一個類BaseNavigationController繼承UINavigationController,然后重寫 -(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated這個方法。所有的push事件都走此方法。

@interface BaseNavigationController : UINavigationController

@end

-(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{

[super pushViewController:viewController animated:animated];

if (self.viewControllers.count>1) {

viewController.hidesBottomBarWhenPushed = YES;

}

}

30、取消系統(tǒng)的返回手勢

self.navigationController.interactivePopGestureRecognizer.enabled = NO;

31、修改UIWebView中字體的大小,顏色

1、UIWebView設置字體大小,顏色,字體:

UIWebView無法通過自身的屬性設置字體的一些屬性,只能通過html代碼進行設置

在webView加載完畢后,在

- (void)webViewDidFinishLoad:(UIWebView *)webView方法中加入js代碼

NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '60%'";

[_webView stringByEvaluatingJavaScriptFromString:str];

或者加入以下代碼

NSString *jsString = [[NSString alloc] initWithFormat:@"document.body.style.fontSize=%f;document.body.style.color=%@",fontSize,fontColor];

[webView stringByEvaluatingJavaScriptFromString:jsString];

歡迎補充。。。

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

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容