通過自己開發(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是一個復合視圖赁严,它是有許多個控件組成的,那么我們就可以從他的內部入手[[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的內容)
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,表示在鍵盤內部滑動扼仲,鍵盤逐漸下去远寸。
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了钠乏,內存泄漏了。
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屬性才能正常顯示多行內容。另外如果出現(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];
歡迎補充。虫腋。骄酗。