1.NSString過濾特殊字符串
定義一個特殊字符的集合
NSCharacterSet set = [NSCharacterSet characterSetWithCharactersInString:@"@/:微驶;()¥「」"综看、[]{}#%-+=\|~<>$€?'@#$%&*()+'""];
過濾字符串的特殊字符
NSString *newString = [NSString stringByTrimmingCharactersInSet:set];
2.TransForm屬性
平移
CGAffineTransform transForm = self.buttonView.transform;
self.buttonView.transform = CGAffineTransformTranslate(transForm, 10, 0);
旋轉(zhuǎn)
CGAffineTransform transForm = self.buttonView.transform;
self.buttonView.transform = CGAffineTransformRotate(transForm, M_PI_4);
縮放
self.buttonView.transform = CGAffineTransformScale(transForm, 1.2, 1.2);
****初始化復(fù)位****
self.buttonView.transform = CGAffineTransformIdentity;
3.計算方法耗時時間間隔
獲取時間間隔
define TICK CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
define TOCK NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)
4.Alert提示宏定義
define Alert(S, …) [[[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:(S), ##VA_ARGS] delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil] show]
5.讓iOS應(yīng)用直接退出
- (void)exitApplication {
AppDelegate *app = [UIApplication sharedApplication].delegate;
UIWindow *window = app.window;
[UIView animateWithDuration:1.0f animations:^{
window.alpha = 0;
} completion:^(BOOL finished) {
exit(0);
}];
}
6.快速求總和 最大值 最小值 和 平均值
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);
7.修改Label中不同文字顏色
(void)touchesEnded:(NSSet<UITouch> *)touches withEvent:(UIEvent *)event
{
[self editStringColor:self.label.text editStr:@"好" color:[UIColor blueColor]];
}-
(void)editStringColor:(NSString *)string editStr:(NSString *)editStr color:(UIColor *)color {
// string為整體字符串, editStr為需要修改的字符串
NSRange range = [string rangeOfString:editStr];NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:string];
// 設(shè)置屬性修改字體顏色UIColor與大小UIFont
[attribute addAttributes:@{NSForegroundColorAttributeName:color} range:range];self.label.attributedText = attribute;
}
8.Label行間距
-(void)test{
NSMutableAttributedString *attributedString =
[[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:3];
//調(diào)整行間距
[attributedString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0, [self.contentLabel.text length])];
self.contentLabel.attributedText = attributedString;
}
9.UIImageView填充模式
@"UIViewContentModeScaleToFill", // 拉伸自適應(yīng)填滿整個視圖
@"UIViewContentModeScaleAspectFit", // 自適應(yīng)比例大小顯示
@"UIViewContentModeScaleAspectFill", // 原始大小顯示
@"UIViewContentModeRedraw", // 尺寸改變時重繪
@"UIViewContentModeCenter", // 中間
@"UIViewContentModeTop", // 頂部
@"UIViewContentModeBottom", // 底部
@"UIViewContentModeLeft", // 中間貼左
@"UIViewContentModeRight", // 中間貼右
@"UIViewContentModeTopLeft", // 貼左上
@"UIViewContentModeTopRight", // 貼右上
@"UIViewContentModeBottomLeft", // 貼左下
@"UIViewContentModeBottomRight", // 貼右下
10.iOS開發(fā)中一些相關(guān)的路徑
//模擬器的位置:
/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
//獲取 iOS 路徑的方法
//獲取家目錄路徑的函數(shù)
NSString *homeDir = NSHomeDirectory();
//獲取Documents目錄路徑的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
//獲取Documents目錄路徑的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];
//獲取tmp目錄路徑的方法:
NSString *tmpDir = NSTemporaryDirectory();
11.關(guān)于隱藏Navigation bar
/*
//設(shè)置滑動的時候隱藏Navigation bar
navigationController.hidesBarsOnSwipe = Yes
//動態(tài)隱藏NavigationBar
*/
1當(dāng)我們的手離開屏幕時候隱藏
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
if(velocity.y > 0)
{
[self.navigationController setNavigationBarHidden:YES animated:YES];
} else {
[self.navigationController setNavigationBarHidden:NO animated:YES];
}
}
PS: velocity.y這個量澎办,在上滑和下滑時赛惩,變化極性斐伞(小數(shù))手蝎,但是因為方向不同榕莺,有正負之分,這就很好處理了
2.在滑動過程中隱藏
(1) self.navigationController.hidesBarsOnSwipe = YES;
(2) 滑動試圖的代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat offsetY = scrollView.contentOffset.y + __tableView.contentInset.top;
CGFloat panTranslationY = [scrollView.panGestureRecognizer translationInView:self.tableView].y;
if (offsetY > 64) {
if (panTranslationY > 0)
{
//下滑趨勢棵介,顯示
[self.navigationController setNavigationBarHidden:NO animated:YES];
} else {
//上滑趨勢钉鸯,隱藏
[self.navigationController setNavigationBarHidden:YES animated:YES];
}
} else {
[self.navigationController setNavigationBarHidden:NO animated:YES];
}
}
PS: 這里的offsetY > 64只是為了在視圖滑過navigationBar的高度之后才開始處理,防止影響展示效果邮辽。panTranslationY是scrollView的pan手勢的手指位置的y值唠雕,可能不是太好,因為panTranslationY這個值在較小幅度上下滑動時吨述,可能都為正或都為負岩睁,這就使得這一方式不太靈敏.
12.自動處理鍵盤事件,實現(xiàn)輸入框防遮擋的插件
https://github.com/hackiftekhar/IQKeyboardManager
13.設(shè)置字體和行間距
1 設(shè)置字體和行間距
UILabel * lable = [[UILabel alloc]initWithFrame:CGRectMake(50, 100, 300, 200)];
lable.text = @"大家好,我是奮拓達,在這里我們一起學(xué)習(xí)新的知識,總結(jié)我們遇到的那些坑,共同的學(xué)習(xí),共同的進步,共同的努力,只為美好的明天!!!有問題一起相互的探討—123456!!!";
lable.numberOfLines = 0;
lable.font = [UIFont systemFontOfSize:12];
lable.backgroundColor = [UIColor grayColor];
[self.view addSubview:lable];
2 設(shè)置每個字體之間的間距
NSKernAttributeName 這個對象所對應(yīng)的值是一個NSNumber對象(包含小數(shù)),作用是修改默認字體之間的距離調(diào)整,值為0的話表示字距調(diào)整是禁用的; NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:lable.text attributes:@{NSKernAttributeName:@(5.0)}];
3 設(shè)置某寫字體的顏色
NSForegroundColorAttributeName 設(shè)置字體顏色
NSRange blueRange = NSMakeRange([[str string] rangeOfString:@"xiao公子"].location, [[str string] rangeOfString:@"Frank_chun"].length);
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:blueRange];
NSRange blueRange1 = NSMakeRange([[str string] rangeOfString:@"123456"].location, [[str string] rangeOfString:@"438637472"].length);
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:blueRange1];
****4 設(shè)置每行之間的間距****
NSParagraphStyleAttributeName 設(shè)置段落的樣式
NSMutableParagraphStyle * par = [[NSMutableParagraphStyle alloc]init];
[par setLineSpacing:20];
*****5 為某一范圍內(nèi)文字添加某個屬性*****
NSMakeRange表示所要的范圍,從0到整個文本的長度
[str addAttribute:NSParagraphStyleAttributeName value:par range:NSMakeRange(0, lable.text.length)]; [lable setAttributedText:str];
14.點擊button倒計時
1第一種方法
// 點擊button倒計時
import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UIButton * timeButton;
@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, strong)UIButton * btn;
@end@implementation ViewController
{
NSInteger _time;
}
- (void)viewDidLoad {
[super viewDidLoad];
_time = 5;
self.btn = [UIButton buttonWithType:UIButtonTypeCustom]; _btn.backgroundColor = [UIColor orangeColor];
[_btn setTitle:@"獲取驗證碼" forState:UIControlStateNormal]; _btn.titleLabel.font = [UIFont systemFontOfSize:15];
[_timeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
[self refreshButtonWidth];
[self.view addSubview:self.btn];
} - (void)refreshButtonWidth{
CGFloat width = 0;
if (_btn.enabled){
width = 100;
} else {
width = 200;
}
_btn.center = CGPointMake(self.view.frame.size.width/2, 200);
_btn.bounds = CGRectMake(0, 0, width, 40);
//每次刷新揣云,保證區(qū)域正確
[_btn setBackgroundImage:[self imageWithColor:[UIColor orangeColor] andSize:_btn.frame.size] forState:UIControlStateNormal];
[_btn setBackgroundImage:[self imageWithColor:[UIColor lightGrayColor] andSize:_btn.frame.size] forState:UIControlStateDisabled];
} - (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)aSize{
CGRect rect = CGRectMake(0.0f, 0.0f, aSize.width, aSize.height); UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
return image;
} - (void)btnAction:(UIButton *)sender{
sender.enabled = NO;
[self refreshButtonWidth];
[sender setTitle:[NSString stringWithFormat:@"獲取驗證碼(%zi)", _time] forState:UIControlStateNormal];
_timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timeDown) userInfo:nil repeats:YES];
} - (void)timeDown{
_time —;
if (_time == 0) {
[_btn setTitle:@"重新獲取" forState:UIControlStateNormal]; _btn.enabled = YES;
[self refreshButtonWidth];
[_timer invalidate];
_timer = nil;
_time = 5 ;
return;
}
[_btn setTitle:[NSString stringWithFormat:@"獲取驗證碼(%zi)", _time] forState:UIControlStateNormal];
}
2 第二種方法
// 點擊發(fā)送驗證碼
- (void)sendMessage:(UIButton )btn{
if (self.phoneField.text.length == 0) {
[self remindMessage:@"請輸入正確的手機號"];
}else{
__block int timeout=60;
//倒計時時間
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue); dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0NSEC_PER_SEC, 0);
//每秒執(zhí)行
dispatch_source_set_event_handler(_timer, ^{
if(timeout<=0){
//倒計時結(jié)束捕儒,關(guān)閉
dispatch_source_cancel(_timer); dispatch_async(dispatch_get_main_queue(), ^{
// 設(shè)置界面的按鈕顯示 根據(jù)自己需求設(shè)置
[btn setTitle:@"發(fā)送驗證碼" forState:UIControlStateNormal]; btn.userInteractionEnabled = YES;
});
}else{
int seconds = timeout % 60;
NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
if ([strTime isEqualToString:@"0"]) {
strTime = [NSString stringWithFormat:@"%d",60];
}
dispatch_async(dispatch_get_main_queue(), ^{
//設(shè)置界面的按鈕顯示 根據(jù)自己需求設(shè)置
//NSLog(@"____%@",strTime);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1];
[btn setTitle:[NSString stringWithFormat:@"%@秒后重新發(fā)送",strTime] forState:UIControlStateNormal];
[UIView commitAnimations];
btn.userInteractionEnabled = NO;
});
timeout—;
}
});
dispatch_resume(_timer);
}
15.修改textFieldplaceholder字體顏色和大小
textField.placeholder = @"username is in here!"; [/p][textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
16.圖片拉伸
UIImage* img=[UIImage imageNamed:@"2.png"];//原圖
UIEdgeInsets edge=UIEdgeInsetsMake(0, 10, 0,10);
UIImageResizingModeStretch:拉伸模式索烹,通過拉伸UIEdgeInsets指定的矩形區(qū)域來填充圖片
UIImageResizingModeTile:平鋪模式桥滨,通過重復(fù)顯示UIEdgeInsets指定的矩形區(qū)域來填充圖
img= [img resizableImageWithCapInsets:edge resizingMode:UIImageResizingModeStretch];
self.imageView.image=img;
17.去掉導(dǎo)航欄下邊的黑線
[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
18.修改pagecontrol顏色
_pageControl.currentPageIndicatorTintColor=SFQRedColor;
_pageControl.pageIndicatorTintColor=SFQGrayColor;
19.去掉UITableView的section的粘性,使其不會懸停
//有時候使用UITableView所實現(xiàn)的列表净当,會使用到section翎迁,但是又不希望它粘在最頂上而是跟隨滾動而消失或者出現(xiàn)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (scrollView == _tableView) {
CGFloat sectionHeaderHeight = 36;
if (scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0) {
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
} else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
}
}
}
20.UIImage與字符串互轉(zhuǎn)
1 圖片轉(zhuǎn)字符串
-(NSString *)UIImageToBase64Str:(UIImage *) image
{
NSData *data = UIImageJPEGRepresentation(image, 1.0f);
NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
return encodedImageStr;
}
2 字符串轉(zhuǎn)圖片
-(UIImage *)Base64StrToUIImage:(NSString *)_encodedImageStr
{
NSData *_decodedImageData = [[NSData alloc] initWithBase64Encoding:_encodedImageStr];
UIImage *_decodedImage = [UIImage imageWithData:_decodedImageData];
return _decodedImage;
}
21.判斷NSString中是否包含中文
-(BOOL)isChinese:(NSString *)str{
NSString *match=@"(^[\u4e00-\u9fa5]+$)";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
return [predicate evaluateWithObject:str];
}
22.NSDate與NSString的相互轉(zhuǎn)化
-(NSString *)dateToString:(NSDate *)date {
// 初始化時間格式控制器
NSDateFormatter *matter = [[NSDateFormatter alloc] init];
// 設(shè)置設(shè)計格式
[matter setDateFormat:@"yyyy-MM-dd hh:mm:ss zzz"];
// 進行轉(zhuǎn)換
NSString *dateStr = [matter stringFromDate:date];
return dateStr;
}
-(NSDate *)stringToDate:(NSString *)dateStr {
// 初始化時間格式控制器
NSDateFormatter *matter = [[NSDateFormatter alloc] init];
// 設(shè)置設(shè)計格式
[matter setDateFormat:@"yyyy-MM-dd hh:mm:ss zzz"];
// 進行轉(zhuǎn)換
NSDate *date = [matter dateFromString:dateStr];
return date;
}
23.控件的局部圓角
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;//設(shè)置路徑
button.layer.mask = mask layer;
24.NavigationBar的透明問題
(1) 如果僅僅是想要navigationBar透明栋猖,按鈕和標題都在可以使用以下方法:
[self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];//給navigationBar設(shè)置一個空的背景圖片即可實現(xiàn)透明,而且標題按鈕都在
PS: 如果僅僅把navigationBar的alpha設(shè)為0的話汪榔,那就相當(dāng)于把navigationBar給隱藏了蒲拉,大家都知道,父視圖的alpha設(shè)置為0的話痴腌,那么子視圖全都會透明的雌团。那么相應(yīng)的navigationBar的標題和左右兩個按鈕都會消失。這樣顯然達不到我們要求的效果士聪。
(2)如果你想在透明的基礎(chǔ)上實現(xiàn)根據(jù)下拉距離锦援,由透明變得不透明的效果,那么上面那個就顯得力不從心了剥悟,這就需要我們采用另外一種方法了
//Navigation Bar是一個復(fù)合視圖灵寺,它是有許多個控件組成的曼库,那么我們就可以從他的內(nèi)部入手
[[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = 0;//這里可以根據(jù)scrollView的偏移量來設(shè)置alpha就實現(xiàn)了漸變透明的效果
25.全局設(shè)置Navigation Bar標題的樣式和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 boldSystemFontOfSize];
26.側(cè)滑手勢返回
iOS的側(cè)滑返回手勢有著很好的操作體驗略板,不支持側(cè)滑返回的應(yīng)用絕對不是好應(yīng)用毁枯。但是在開發(fā)過程中在自定義了返回按鈕,或者某些webView,tableView等頁面叮称,側(cè)滑返回手勢失效种玛,這時候就需要我們來進行設(shè)置一下了,可以在基類里面協(xié)商如下代碼:
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
//需要遵循一下手勢的代理 self.navigationController.interactivePopGestureRecognizer.delegate = self;
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}
問題:當(dāng)返回navigationController的最頂層的Controller的時候。再次側(cè)滑瓤檐,這個時候你在點擊一個push頁面的操作赂韵,你會發(fā)現(xiàn)卡那了,半天才會有反應(yīng)距帅。
解釋 :這是由于右锨,在最頂層Controller手勢依然有效,但是滑動后碌秸,并找不到返回的頁面。造成軟件卡頓悄窃,假死所以就要在rootViewController中讓此手勢失效讥电。把下面的設(shè)為NO
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
PS :當(dāng)然你也可以使用一個第三方庫,寫的相當(dāng)棒轧抗。他對系統(tǒng)的側(cè)滑返回手勢進行拓展恩敌,不用從邊緣滑動,只要右滑即可返回横媚。最重要的是纠炮,他只需要加入項目中即可,不需要一行代碼即可實現(xiàn)灯蝴。附上github 網(wǎng)址
https://github.com/forkingdog/FDFullscreenPopGesture
27.給webView添加頭視圖
webView是一個復(fù)合視圖恢口,里面包含有一個scrollView,scrollView里面是一個UIWebBrowserView(負責(zé)顯示W(wǎng)ebView的內(nèi)容)
UIView webBrowserView = self.webView.scrollView.subviews[0];//拿到webView的webBrowserView
self.backHeadImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth2/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的高度穷躁,使其可見
28.模態(tài)跳轉(zhuǎn)的動畫設(shè)置 Model
DetailViewController *detailVC = [[DetailViewController alloc]init];
UIModalTransitionStyleFlipHorizontal 翻轉(zhuǎn)
UIModalTransitionStyleCoverVertical 底部滑出
UIModalTransitionStyleCrossDissolve 漸顯
UIModalTransitionStylePartialCurl 翻頁
detailVC.modalTransitionStyle = UIModalTransitionStylePartialCurl;
[self presentViewController:detailVC animated:YES completion:nil];
29.圖片處理只拿到圖片的一部分
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)就是圖片的全尺寸猿诸,想取哪一部分就設(shè)置相應(yīng)坐標即可
CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, rect);
UIImage *imageRect = [[UIImage alloc] initWithCGImage:imageRefRect];
30.給UIView設(shè)置圖片
UIImage *image = [UIImage imageNamed:@"playing"];
_layerView.layer.contents = (__bridge id)image.CGImage;
_layerView.layer.contentsCenter = CGRectMake(0.25, 0.25, 0.5, 0.5);
//同樣可以設(shè)置顯示的圖片范圍
//不過此處略有不同,這里的四個值均為0-1之間狡忙;對應(yīng)的依然是寫x,y,widt,height
31.給TableView或者CollectionView的cell添加簡單動畫 (只要在willDisplayCell方法中對將要顯示的cell做動畫即可)
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
NSArray *array = tableView.indexPathsForVisibleRows;
NSIndexPath *firstIndexPath = array[0];
//設(shè)置anchorPoint
cell.layer.anchorPoint = CGPointMake(0, 0.5);
//為了防止cell視圖移動梳虽,重新把cell放回原來的位置
cell.layer.position = CGPointMake(0, cell.layer.position.y);
//設(shè)置cell 按照z軸旋轉(zhuǎn)90度,注意是弧度
if (firstIndexPath.row < indexPath.row) {
cell.layer.transform = CATransform3DMakeRotation(M_PI_2, 0, 0, 1.0);
}else{
cell.layer.transform = CATransform3DMakeRotation(- M_PI_2, 0, 0, 1.0);
}
cell.alpha = 0.0;
[UIView animateWithDuration:1 animations:^{
cell.layer.transform = CATransform3DIdentity;
cell.alpha = 1.0;
}];
}
32.兩點之間的距離 & 線程中更新UILabel的text
1 兩點之間的距離
static__inline__ CGFloat CGPointDistanceBetweenTwoPoints(CGPoint point1, CGPoint point2) {
CGFloat dx = point2.x - point1.x; CGFloat dy = point2.y - point1.y;
returnsqrt(dxdx + dydy);
}
2 線程中更新UILabel的text
abel1為UILabel灾茁,當(dāng)在子線程中窜觉,需要進行text的更新的時候谷炸,可以使用這個方法來更新。
其他的UIView也都是一樣的竖螃。
[self.label1 performSelectorOnMainThread:@selector(setText:) withObject:textDisplay waitUntilDone:YES];
33.獲得當(dāng)前硬盤空間
NSFileManagerfm = [NSFileManagerdefaultManager];
NSDictionaryfattributes = [fmattributesOfFileSystemForPath:NSHomeDirectory()error:nil];
NSLog(@"容量%lldG",[[fattributesobjectForKey:NSFileSystemSize]longLongValue]/1000000000);
NSLog(@"可用%lldG",[[fattributesobjectForKey:NSFileSystemFreeSize]longLongValue]/1000000000);
34.ActivityViewController使用AirDrop分享
使用AirDrop進行分享:
NSArray array =@[@"test1",@"test2"];
UIActivityViewControlleractivityVC = [[UIActivityViewController alloc] initWithActivityItems:array applicationActivities:nil];
[selfpresentViewController:activityVCanimated:YES
completion:^{
NSLog(@"Air");
}];
35.保存全屏為image
CGSizeimageSize = [[UIScreenmainScreen]bounds].size;
UIGraphicsBeginImageContextWithOptions(imageSize,NO,0);
CGContextRefcontext =UIGraphicsGetCurrentContext();
for(UIWindow* windowin[[UIApplicationsharedApplication]windows]) {
if(![windowrespondsToSelector:@selector(screen)] || [windowscreen] == [UIScreenmainScreen]) {
CGContextSaveGState(context);
CGContextTranslateCTM(context, [windowcenter].x, [windowcenter].y);
CGContextConcatCTM(context, [windowtransform]);
CGContextTranslateCTM ( context, -[windowbounds].size.width *[[windowlayer]anchorPoint].x, -[windowbounds].size.height [[windowlayer]anchorPoint].y);
[[windowlayer]renderInContext:context];
CGContextRestoreGState(context);
}
}
UIImageimage = UIGraphicsGetImageFromCurrentImageContext();
36.獲取通訊錄聯(lián)系人的電話號碼
import
import
ABPeoplePickerNavigationControllerDelegate
- (void)addAddress {
RYLog(@"選擇聯(lián)系人");
ABPeoplePickerNavigationController * vc =[[ABPeoplePickerNavigationController alloc] init];
vc.peoplePickerDelegate =self;
[selfpresentViewController:vc animated:YEScompletion:nil];
}
pragma mark -- ABPeoplePickerNavigationControllerDelegate
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
ABMultiValueRef valuesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);
CFIndex index = ABMultiValueGetIndexForIdentifier(valuesRef,identifier);
//電話號碼
CFStringRef telValue = ABMultiValueCopyValueAtIndex(valuesRef,index);
[selfdismissViewControllerAnimated:YEScompletion:^{
self.addressV.telnum.text = (__bridgeNSString *)telValue;
}];
}
37.用WebView加載頁面淑廊,提前獲取頁面的高度
可以獲得內(nèi)容高度,但是網(wǎng)絡(luò)不好時特咆,不準確
1.webView.scrollView.contentSize.height;
獲取的高度較為準確
2.[[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"] intValue]