从代码可移植性的角度来看,纯手写代码 > xib界面文件 > storyboard
从代码复杂度的角度来看,storyboard > xib 界面文件 > 纯手写代码
弹出提示框
[UIAlertView alloc]initWithTitle
iOS 8 建议使用 UIAlertController
改变UIAlertController的标题、内容的字体和颜色
[UIView appearance].tintColor = [UIColor colorWithHexString:DSBlackColor];
能够统一修改按钮字体颜色。
分享功能实现:
UIActivityViewController
简单的系统 Loading效果 UIActivityIndicatorView
支持横屏
Orientation 设置,而后把它从Inferred修改成 Landscape。 (General选项
Device Orientations 取消选中Portrait这个选项)。
lroundf 四舍五入到最接近的整数(long int)
方法与函数
// 下面的这个是方法:
[someObject methodName:parameter];
// 下面的这个是函数:
SomeFunction(parameter);
方法确定是对象的方法,函数不属于某个对象
在dicload 里面定义一些 类变量的初值;
在用到属性的地方几乎都要用到self关键词:
// 属性: self.slider.value = 50; @property
// 属性“背后”的实例变量: slider.value = 50; @synthesize 建立的实例变量 (uislider *) slider
独立的方法,多个地方能够调用,而且清晰,好维护
// 动做方法,(IBAction)能够和界面中的控件创建关联
- (IBAction)buttonTapped:(UIButton *)button;
静态/动态类型语言:
静态语言(C,C++,C#,Objective-C,Java)数据类型肯定、提早分配内存空间,编译时检查
动态语言(Python,Ruby,PHP,JavaScript,Erlang),不须要指定数据类型,运行时记录数据类型。
强/弱类型定义语言
脚本语言/通用语言
解释型语言/编译语言
视图控制器 能够监听来自提示对话框的事件,经过设置UIAlertViewDelegate 代理
多界面:
new file > class >
storyboard:
1. 按住control 拖动按钮到新的View controller 选择modal ,建立点击跳转事件
2. [self.presentingViewController dismissViewControllerAnimated:YES completion:nil]; 退出新视图
xib 文件,按住control 拖动按钮到 .m,action点击事件,方法定义:
1. 定义
AboutViewController *controller = [[AboutViewController alloc]initWithNibName:@"AboutViewController" bundle:nil];
alloc initWithNibName 经过xib文件 初始化新视图,
2. controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; 定义跳转动画
3. [self presentViewController:controller animated:YES completion:nil]; 经过动画,展示新视图
4. 在新视图的.m button action中定义退出视图[self.presentingViewController dismissViewControllerAnimated:YES completion:nil]; 退出新视图
隐藏状态栏
1.Supporting Files 》 CrazyDrag-Info.plist 》Add Row 》View controller-based status bar appearance 在Value那里设置为NO
2.项目名 》Deployment Info 》Status Bar Style下面的Hide during application launch
修改状态栏颜色
第一步:在info.plist中添加一个字段:view controller -base status bar 设置为NO
第二步:
if ( >ios7) { // 判断是不是IOS7
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
}
iOS 9以后
程序启动顺序:
1. 入口 main.m
2.自动调用UIApplicationMain ,初始化一个应用对象,使用指定的类名称初始化一个代理,设置程序的主Event loop。 读取plist UIMainStoryBoardFile.
3. 自动调用代理,初始化主界面
4. 进入视图控制器,等待交互。
UINavigationBar 增长 ButtonItem (扩展性,样式很差调整,建议采用自定义)
UIButton *questionBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 27, 25)];
[questionBtn setBackgroundImage:[UIImage imageNamed:@"icon_send"] forState:UIControlStateNormal];
[questionBtn addTarget:self action:@selector(sendClick:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithCustomView:questionBtn];
self.navigationItem.rightBarButtonItem = leftBtn;
self.navigationItem.leftBarButtonItems = [NSArray arraywithobjects:leftBtn,rightBtn,nil];
UIBarButtonItem *addNewScheduleBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"add_img"] style:UIBarButtonItemStyleBordered target:self action:@selector(clickRightButton)];
[self.navigationItem setRightBarButtonItem:addNewScheduleBtn];
图片拉伸
stretchableImageWithLeftCapWidth 一个内容可拉伸,而边角不拉伸的图片,第一个是左边不拉伸区域的宽度,第二个参数是上面不拉伸的高度
[image resizableImageWithCapInsets:UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)]; // 上下左右 四个角不可拉伸
CATransition 动画效果
self.view.layer addAnimation:transition forKey:nil]; view使用这个动画过渡效果。
#import <AVFoundation/AVFoundation.h> 播放音频视频
AVAudioPlayer
页面跳转
navigationController pushViewController:controller
[self.navigationController popToRootViewController]
返回指定的某个vc用下面
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:2] animated:YES];
UIView可交互
userInteractionEnabled = YES; UIView 默认是YES,UIView接受并响应用户的交互。 可是UIImageView 是NO 须要设置YES视图和子视图才能响应用户交互。
字体、行距
btn.titleLabel.font = [UIFont systemFontOfSize: 14.0]; button 修改字体方法。
boldSystemFontOfSize 粗体字
button setImage 设置背景图
label.numberOfLine =2 ; 设置最大行数
[label sizetoFit]; 自动调整size
uiwebview 控制字体行间距 NSString *webviewText = @"<style>body{margin:0;background-color:transparent;font:16px/18px Custom-Font-Name}</style>”;
UILabel 行间距
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:contentLabel.text];;
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
[paragraphStyle setLineSpacing:5];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, contentLabel.text.length)];
contentLabel.attributedText = attributedString;
//调节高度
CGSize size = CGSizeMake(width, 500000);
CGSize labelSize = [contentLabel sizeThatFits:size];
json 解析返回的<null>处理:
if ([latitude isEqual:[NSNull null]])
NSMutableAttributedText
富文本,实现UILabel UIButton UITextView中文字不一样颜色和字体。
NSFontAttributeName (字体) NSForegroundColorAttributeName (字体颜色)
NSStokeWidthAttributeName :@-5 NSStrokeColorAttributeName:[uicolor redColor] (描边)
NSBackgroundColorAttributeName:transparentYellow;
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Using NSAttributed String"];
[str setAttributes] removeAttributes
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,5)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:30.0] range:NSMakeRange(0, 5)];
NSAttributedString *attributedString = ;
NSString *subString = ;
[attributedString string] rangeOfString:subString];
UILabel的 attributedText只读:
NSMutableAttributedString *labelText = [myLabel.attributedText mutableCopy];
[labelText setAttributes:<#(NSDictionary *)#> range:<#(NSRange)#>];
myLabel.attributedText = labelText;
下划线 删除线 label:
UILabel 现实带html标签的文本:
GONMarkupParser.h
uitextview 禁止编辑 :.editable = NO;
控件隐藏 .hidden = YES;
[cell.contentView viewWithTag:tag]; 获取cell中的子控件,经过tag
[view removeformsupview]; 移除view
[ 值 floatvalue]; id类型转化为float
[NSString stringWithFormat:@"%.02f%%",someFloat]; stringWithFormat 显示百分号的实现。
cell 添加到 nsmuarray 这样就能够遍历须要的cell
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
cell 动态调节高度
/* UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
return cell.frame.size.height;
*/ 根据cell内容 在cellForRowAtIndexPath:indexPath 中设置cell.frame, 用于动态调节row的高度。
限制textView 最大输入字数
textView:(UITextView *)textView shouldChangeTextInRange:
{
if (range.location>=140)
{
return NO;
}
else
{
return YES;
}
}
通知中心:
// 发送通知
[[NSNotificationCenter defaultCenter] postNotificationName:kLoginSucceedNotificationKey object:testArray];
---
// 注册通知事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSucceed:) name:kLoginSucceedNotificationKey object:nil];
// 处理通知事件
-(void)loginSucceed:(NSNotification*)aNotification
{
NSMutableArray* dataArray = [aNotification object]; // 获取到发送通知的参数
}
// 处理完成后, 移除通知
[[NSNotificationCenter defaultCenter] removeObserver:self name:kLoginSucceedNotificationKey object:nil];
本地通知:
解析本地Json
NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"TeamMembers" ofType:@"json"]];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
经过POST请求URL解析json
NSURL *url = [NSURL URLWithString:URLString];
//第二步,建立请求
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
[request setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET
NSString *str = [NSString stringWithFormat:@"user_id=%d&title=%@&text=%@",[self.currentUser uid],[NSString stringWithFormat:@"%@的工做日报",dateFormat],contentText.text];//设置参数
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
//第三步,链接服务器
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSDictionary *myDic = nil;
if (response) {
myDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:nil];
}
NSDictionary ,转化为Json结构的 NSString
NSDictionary *dataDict = [[NSDictionary alloc] initWithObjectsAndKeys:method,@"Method", version, @"Version", appID, @"AppID", params,@"Params",key, @"Key", sessionID, @"SessionID", nil];
//dictionary 转化为 data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dataDict options:NSJSONWritingPrettyPrinted error:&parseError];
//Data转换为JSON string
NSString* jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
控件边框
导入QuartzCote框架:
#import <QuartzCore/QuartzCore.h>
设置边框:
textView.layer.borderColor = [UIColorgrayColor].CGColor;
textView.layer.borderWidth =1.0;
textView.layer.cornerRadius =5.0;
判断输入框是否为空:
textView.text.length ==0
Xcode运行缓存:
删除/Users/用户名/Library/Developer/Xcode/DerivedData 路径下的缓存文件 Xcode clean
arc 支持/ 非arc支持
-fobjc-arc / -fno-objc-arc
关于Build Active Architecture Only属性
这个属性设置为yes,是为了debug的时候编译速度更快,它只编译当前的architecture版本。
而设置为no时,会编译全部的版本。
这个是设备对应的architecture:
armv6:iPhone 2G/3G,iPod 1G/2G
armv7:iPhone 3GS/4/4s,iPod 3G/4G,iPad 1G/2G/3G
armv7s:iPhone5, iPod5
编译出的版本是向下兼容的,好比你设置此值为yes,用iphone4编译出来的是armv7版本的,iphone5也能够运行,可是armv6的设备就不能运行。
因此,通常debug的时候能够选择设置为yes,release的时候要改成no,以适应不一样设备。
NSString 处理空格和回车
去除两端空格
NSString *temp = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
去除两端空格和回车
NSString *text = [temp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet ]];
lineBreakMode:设置标签文字过长时的显示方式。
label.lineBreakMode = NSLineBreakByCharWrapping;//以字符为显示单位显示,后面部分省略不显示。
label.lineBreakMode = NSLineBreakByClipping;//剪切与文本宽度相同的内容长度,后半部分被删除。
label.lineBreakMode = NSLineBreakByTruncatingHead;//前面部分文字以……方式省略,显示尾部文字内容。
label.lineBreakMode = NSLineBreakByTruncatingMiddle;//中间的内容以……方式省略,显示头尾的文字内容。
label.lineBreakMode = NSLineBreakByTruncatingTail;//结尾部分的内容以……方式省略,显示头的文字内容。
label.lineBreakMode = NSLineBreakByWordWrapping;//以单词为显示单位显示,后面部分省略不显示。
IOS Reachability
在子线程中,界面的刷新、更新,通常要回到主线程中处理:
dispatch_async(dispatch_get_main_queue(), ^{
debugLog(@"resultDict--%@",resultDict);
[self parseDataWithDict:resultDict];
[self hideLoading];
});
popToViewController用法 pop到肯定的viewController
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:2] animated:YES];
或
for (UIViewController *controller inself.navigationController.viewControllers) {
if ([controller isKindOfClass:[你要跳转到的Controller class]]) {
[self.navigationControllerpopToViewController:controller animated:YES];
}
}
调起本地图片/ 相机
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
if (buttonIndex != 2) {
debugLog(@"拍照");
BOOL hasCamera = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];//判断照相机是否可用(是否有摄像头)
if (hasCamera) {
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
}
{
debugLog(@"本地图片");
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
}
picker.delegate = self;
// picker.allowsEditing = YES; //是否可编辑
[self presentViewController:picker animated:YES completion:nil];
将subview 置于supview 最顶层
[parentView bringSubviewToFront:subview];
延迟执行
[self performSelector:@selector(delayMethod) withObject:nil afterDelay:1.0f];
此方式要求必须在主线程中执行,不然无效。
是一种非阻塞的执行方式,
暂时未找到取消执行的方法。
定位:
core.location CLLocationManager
tableview 上拉加载更多 下拉刷新,写在baseviewController中,tableviewController共用。
UIActivityViewController iOS 系统分享
使用iOS7系统 的侧边栏返回手势
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}
[NSUserDefaults standardUserDefaults]
NSUserDefaults支持的数据格式有:NSNumber(Integer、Float、Double),NSString,NSDate,NSArray,NSDictionary,BOOL类型。
NSUserDefaults偶尔不工做,没法保存改动的数据的缘由是,NSUserDefaults的机制是,过一段时间,会自动调用本身的函数synchronize去同步数据的。
而若是改动数据后,就退出程序了,即在NSUserDefaults还没来得及synchronize以前就退出程序,就须要手动调用synchronize去保存数据了。
即,在须要的时候,手动调用NSUserDefaults去执行同步synchronize的动做,以及时保存(set 修改了的)数据。
各个控件内边距方法
uibutton 文字位置 (内边距)
btn.contentHorizontalAlignment = UIControlContentHorizonAlignmentLeft;
btn.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 0);
使文字距离作边框保持10个像素的距离。
UITextView contentInset
UITextField setValue:[NSNumber numberWithInt:5] forKey:@"paddingTop"];paddingLeft/paddingBottom/paddingRight
UIView 子类超出bounds不显示
uiview.layer.maskToBounds = YES;
点击手势和其余控件点击冲突
tapGesture.delegate = self;
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
CGPoint location = [touch locationInView:self.view];
if(CGRectContainsPoint(button.frame, location))
{
return NO;
}
return YES;
//或者经过view 的class判断
// if([touch.view isKindOfClass:[UIButton class]])
// {
// return NO;
// }
// return YES;
}
UIButton setBackgroundImage和setImage 区别
首先setBackgroundImage,image会随着button的大小而改变,图片自动会拉伸来适应button的大小,这个时候仍然能够设置button的title,image不会挡住title;
相反的的setImage,图片不会进行拉伸,原比例的显示在button上,此时再设置title,title将没法显示;
[btn.imageView setContentMode:UIViewContentModeScaleAspectFill]; 能够设置setImage的image显示形式。
UIButton 字体位置
btn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft ;//设置文字位置,现设为居左,默认的是居中
获取非子视图 在view中的位置
CGRect rect = [self.view convertRect:sender.frame fromView:sender.superview];
触碰就收起键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];
}
NSString 和 NSURL的互相转换
NSString *str = @"";
NSURL *URL = [NSURL URLWithString:str]; //string>url
NSString *str1 = [URL absoluteString]; //url>string
获取手势点击的view
- (void)imageTouch:(UITapGestureRecognizer * )sender
{
UIView *view = sender.self.view; // 这个view 就是点击的那个控件
}
复制字符串到剪贴板
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = self.label.text;
压缩图片分别率
+ (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
// Create a graphics image context
UIGraphicsBeginImageContext(newSize);
// Tell the old image to draw in this new context, with the desired
// new size
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
// Get the new image from the context
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
// End the context
UIGraphicsEndImageContext();
// Return the new image.
return newImage;
}
UIView转成 image
+ (UIImage*)convertViewToImage:(UIView*)v{
CGSize s = v.bounds.size;
// 下面方法,第一个参数表示区域大小。第二个参数表示是不是非透明的。若是须要显示半透明效果,须要传NO,不然传YES。第三个参数就是屏幕密度了
UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
[v.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
//截取部分图像
-(UIImage*)getSubImage:(CGRect)rect
{
CGImageRef subImageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
CGRect smallBounds = CGRectMake(0, 0, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));
UIGraphicsBeginImageContext(smallBounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, smallBounds, subImageRef);
UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
UIGraphicsEndImageContext();
return smallImage;
}
图片保存到文件路径
[UIImagePNGRepresentation(tempImg) writeToFile:photoPath atomically:YES];
一步步调试解决iOS内存泄漏
iOS应用如何实现64位的支持
CocoaPods安装和使用教程
http://code4app.com/article/cocoapods-install-usage
AFNetworking
http://blog.csdn.net/daiyelang/article/details/38421341
iOS8 中 全局webview 加入tableviewcell.contentView 不显示.
[[UIColor redColor] colorWithAlphaComponent:0.3];
随机整数(0~ 100)
unsigned index = arc4random() % 100;
【教程】如何设置launchImage显示的时间
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[NSThread sleepForTimeInterval:2.0]; //设置进程中止2秒
}
presentViewController 的 ViewController 获取 self.presentingViewController, iOS8之前的系统 在viewWillAppear 获取,在其余地方可能会为nil, 设置一个属性,在viewWillAppear中设置set属性。其余地方能够调用。
解决uiscrollView 截获uiview 的touch 事件解决方法
#import "UIScrollView+UITouch.h"
@implementation UIScrollView (UITouch)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[[self nextResponder] touchesBegan:touches withEvent:event];
[super touchesBegan:touches withEvent:event];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[[self nextResponder] touchesMoved:touches withEvent:event];
[super touchesMoved:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[[self nextResponder] touchesEnded:touches withEvent:event];
[super touchesEnded:touches withEvent:event];
}
图像翻转,旋转
imageView 是一个UIImageView的实例
//左右flip
imageView.transform = CGAffineTransformMakeScale(-1.0, 1.0);
//上下flip
imageView.transform = CGAffineTransformMakeScale(1.0,-1.0);
//缩放,中心点固定
imageView.transform = CGAffineTransformMakeScale(0.1,0.1);
imageView.transform = CGAffineTransformMakeScale(2.0,2.0);
// 旋转一个角度
imageView.transform = CGAffineTransformMakeRotation(90*M_PI/180);
数据存储成plist文件
NSArray *localtionArray = dic[@"data"];
NSString *documentsDirectory = PATH_OF_DOCUMENT;
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"city.plist"];
[localtionArray writeToFile:filePath atomically:YES]; // 保存数据
(若是保存的是比较复杂的数据,里面包含对象,能够转化为NSData,进行存取)
NSData * data = [NSKeyedArchiver archivedDataWithRootObject:_historyCity];
[data writeToFile:filePath atomically:YES]; // 保存数据
NSData * data1 = [NSData dataWithContentsOfFile:filePath];// 读取数据
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data1];
NSString *documentsDirectory = PATH_OF_DOCUMENT;
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"city.plist"];
areaArray = [[NSArray alloc] initWithContentsOfFile:plistPath]; // 读取数据
修改 placeholder 颜色
[_userName setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
uiview添加边框、阴影
contentBgView.layer.borderColor = [UIColor colorWithHexString:@"e0e0e0"].CGColor;
contentBgView.layer.borderWidth = 0.5f;
contentBgView.layer.shadowColor = [UIColor blackColor].CGColor;//shadowColor阴影颜色
contentBgView.layer.shadowOffset = CGSizeMake(0,2);//shadowOffset阴影偏移,x向右偏移4,y向下偏移4,默认(0, -3),这个跟shadowRadius配合使用
contentBgView.layer.shadowOpacity = 0.4;//阴影透明度,默认0
contentBgView.layer.shadowRadius = 2;//阴影半径,默认3
UItextView 高度根据内容自适应
CGRect textFrame;
textFrame=textView.frame;
CGSize constraint = CGSizeMake(textFrame.size.width, 99999.0f);
CGSize size = [textView sizeThatFits:constraint];
textFrame.size.height = MAX(size.height, 32);
[textView setFrame:textFrame];
或者:
CGRect textFrame;
textFrame=textView.frame;
textFrame.size.height= MAX(32, textView.contentSize.height);
[textView setFrame:textFrame];
NSArray 的遍历,倒序遍历
NSArray 删除重复项,能够转换为NSSet 再转为NSArray
NSSet *set = [NSSet setWithArray:arr];
NSArray *sortDesc = @[[[NSSortDescriptor alloc] initWithKey:nil ascending:YES]];
NSArray *sortSetArray = [set sortedArrayUsingDescriptors:sortDesc];
enumerateObjectsUsingBlock 是安全的,能够用于遍历时候删除数组元素。
[marrayA enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isEqualToString:@"a"]) {
[marrayA removeObject:obj];
}
}];
NSArray和NSOrderedSet都支持使用reverseObjectEnumerator倒序遍历,如:
NSArray *strings = @[@"1", @"2", @"3"];
for (NSString *string in [strings reverseObjectEnumerator]) {
NSLog(@"%@", string);
}
这个方法只在循环第一次被调用,因此也没必要担忧循环每次计算的问题。
同时,使用enumerateObjectsWithOptions:NSEnumerationReverse也能够实现倒序遍历:
[array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(Sark *sark, NSUInteger idx, BOOL *stop) {
[sark doSomething];
}];
使用block同时遍历字典key,value
block版本的字典遍历能够同时取key和value(forin只能取key再手动取value),如:
NSDictionary *dict = @{@"a": @"1", @"b": @"2"};
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"key: %@, value: %@", key, obj);
}];
对于耗时且顺序无关的遍历,使用并发版本
[array enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(Sark *sark, NSUInteger idx, BOOL *stop) {
[sark doSomethingSlow];
}];
label.adjustsFontSizeToFitWidth //文本文字自适应大小
使用cell默认分割线时候,怎么让左对齐
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([cell respondsToSelector:@selector(setSeparatorInset:)])
{
[cell setSeparatorInset:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)])
{
[cell setPreservesSuperviewLayoutMargins:NO];
}
if ([cell respondsToSelector:@selector(setLayoutMargins:)])
{
[cell setLayoutMargins:UIEdgeInsetsZero];
}
// 待尝试
[cell setSeparatorInset:UIEdgeInsetsZero];
[cell setLayoutMargins:UIEdgeInsetsZero];
}
1. webview 加载gif文件
// 读取gif图片数据
NSData *gif = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"guzhang" ofType:@"gif"]];
// view生成
UIWebView *webView = [[UIWebView alloc] initWithFrame:frame];
webView.userInteractionEnabled = NO;//用户不可交互
[webView loadData:gif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
[self.view addSubview:webView];
2. UIImageView animationImages
gifImageView.animationImages = gifArray; //动画图片数组
gifImageView.animationDuration = 5; //执行一次完整动画所需的时长
gifImageView.animationRepeatCount = 1; //动画重复次数
[gifImageView startAnimating];
[self.view addSubview:gifImageView];
NSArray NSMutableArray 相互转化
// NSArray --> NSMutableArray
NSMutableArray *myMutableArray = [myArray mutableCopy];
// NSMutableArray --> NSArray
NSArray *myArray = [myMutableArray copy];
SDWebImage 清理缓存
[[SDImageCache sharedImageCache] clearDisk];
float tmpSize = [[SDImageCache sharedImageCache] checkTmpSize];
NSString *clearCacheName = tmpSize >= 1 ? [NSString stringWithFormat:@"清理缓存(%.2fM)",tmpSize] : [NSString stringWithFormat:@"清理缓存(%.2fK)",tmpSize * 1024];
sdwebimage 获取已缓存的图片:
UIImage *originalImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:urlStr];
SDWebImage 加进度条
跑马灯效果 MarqueeLabel
autolayout Label 根据内容设置宽度
[_sumPriceLabel mas_updateConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(_sumPriceLabel.intrinsicContentSize.width);
}];
纯单色的icon 能够用 iconFont 作图标, 至关于把图标定义成一种字体,设置UI控件的text 就能够显示对应图标。 icon 转为iconfont.ttf 字体文件
_leftButton.titleLabel.font = [UIFont fontWithName:@"iconfont" size:25];
[_leftButton setTitle:[IconFont sharedInstance].fanhui forState:UIControlStateNormal];
系统base64 转码 (iOS7+):
NSData* originData = [originStr dataUsingEncoding:NSASCIIStringEncoding];
NSData *data = UIImagePNGRepresentation(image);
NSString *str = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
NSData* decodeData = [[NSData alloc] initWithBase64EncodedString:encodeResult options:0];
NSString* decodeStr = [[NSString alloc] initWithData:decodeData encoding:NSASCIIStringEncoding];
清除缓存
缓存文件夹路径:
NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
AES加密
MD5 加密
WKWebView iOS8 WebKit库之——WKWebView篇
关于wkwebview js交互用户
(wkWebView 直接alloc init 会有内存泄漏 ,使用如下方式初始化
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
config.selectionGranularity = WKSelectionGranularityCharacter;
_wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) configuration:config];
// _wkWebView.UIDelegate = self;
_wkWebView.navigationDelegate = self;
[self.view addSubview:_wkWebView];
)
UITableView,UIScrollView的时候有时候会偏移20像素
在ios7里面若是有滚动视图的时候,好比UITableView,UIScrollView的时候有时候会偏移20像素。这时候能够这样设置
if ([[UIDevice currentDevice] systemVersion].floatValue>=7.0) {
self.automaticallyAdjustsScrollViewInsets = NO;
}
self.edgesForExtendedLayout = UIRectEdgeNone; 视图延伸,
edgesForExtendedLayout是一个类型为UIExtendedEdge的属性,指定边缘要延伸的方向。
由于iOS7鼓励全屏布局,它的默认值很天然地是UIRectEdgeAll,四周边缘均延伸,就是说,若是即便视图中上有navigationBar,下有tabBar,那么视图仍会延伸覆盖到四周的区域
iOS8以上定位
{
//定位管理器
_locationManager=[[CLLocationManager alloc]init];
if (![CLLocationManager locationServicesEnabled]) {
[HUD showText:@"定位服务当前可能还没有打开,请设置打开!"];
return;
}
//设置代理
_locationManager.delegate=self;
//设置定位精度
_locationManager.desiredAccuracy=kCLLocationAccuracyBest;
//定位频率,每隔多少米定位一次
CLLocationDistance distance=10.0;//十米定位一次
_locationManager.distanceFilter=distance;
if (IOS_VERSION >=8) {
[_locationManager requestWhenInUseAuthorization];//使用程序其间容许访问位置数据(iOS8定位须要)
}
//启动跟踪定位
[_locationManager startUpdatingLocation];
}
#pragma mark - CoreLocation 代理
#pragma mark 跟踪定位代理方法,每次位置发生变化即会执行(只要定位到相应位置)
//能够经过模拟器设置一个虚拟位置,不然在模拟器中没法调用此方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *location=[locations lastObject];//取出当前位置
if (location) {
CLLocationCoordinate2D coordinate= [LocationCorrection transformFromWGSToGCJ:location.coordinate];//位置坐标
NSLog(@"经度:%f,纬度:%f,海拔:%f,航向:%f,行走速度:%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
//若是不须要实时定位,使用完即便关闭定位服务
[_locationManager stopUpdatingLocation];
self.currentLocation = [[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
[[NSNotificationCenter defaultCenter] postNotificationName:@"locationSucess" object:nil userInfo:nil];
//获取所在地城市名
CLGeocoder *geocoder=[[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:_currentLocation completionHandler:^(NSArray *placemarks,NSError *error)
{
for(CLPlacemark *placemark in placemarks)
{
self.currentCity = [placemark.addressDictionary objectForKey:@"City"];
debugLog(@"str%@",_currentCity);
[[NSNotificationCenter defaultCenter] postNotificationName:@"locationCitySucess" object:nil userInfo:nil];
}
}];
}
}
二、在Info.plist文件中添加以下配置:
(1)NSLocationAlwaysUsageDescription
(2)NSLocationWhenInUseUsageDescription
正则 判断手机号
+ (BOOL)validatePhoneNum:(NSString *)phoneNum
{
NSString *mobileRegex = @"^((13[0-9])|(147)|(170)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
NSPredicate *mobileTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",mobileRegex];
BOOL n = [mobileTest evaluateWithObject:phoneNum];
return n;
}
UITabbar
// 去除tabBar顶部默认阴影线
[self.tabBar setClipsToBounds:YES];
[[UITabBar appearance] setShadowImage:[[UIImage alloc]init]];
// 解决iOS8 默认蓝色高亮的问题。
tabImage = [tabImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
网络图片保存到相册
NSURLCache *cache =[NSURLCache sharedURLCache];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:src]];
NSData *imgData = [cache cachedResponseForRequest:request].data;
UIImage *image = [UIImage imageWithData:imgData];
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
关于UISearchDisplayController
tableView视图下拉拉伸效果
3D touch
倒计时
获取TableViewCell上button所在的行数
在自定义的 cell 上面放了一个 button, 除了经过 cell.btn.tag 值获取cell的行数以外,另外一种方即可行的方式。
[cell.btn addTarget:self action:@selector(cellBtnClicked:event:) forControlEvents:UIControlEventTouchUpInside];
-(void)cellBtnClicked:(id)sender event:(id)event {
NSSet *touches =[event allTouches];
UITouch *touch =[touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:_tableView];
NSIndexPath * indexPath = [_tableView indexPathForRowAtPoint:currentTouchPosition];
(indexPath!= ) {
// do something
}
}
po [view recursiveDescription] 显示视图中的层级关系。
在不改变按钮尺寸的前提下,扩大按钮的点击范围
textfield 的输入字数/不限制光标字数
绝对值:int abs(int i); // 处理int类型的取绝对值 double fabs(double i); //...float fabsf(float i); /
__FUNCTION__ 打印方法名
keyChain and TouchID
一般状况下,咱们用NSUserDefaults存储数据信息,可是对于一些私密信息,好比密码、证书等等,就须要使用更为安全的keychain了。keychain里保存的信息不会因App被删除而丢失,在用户从新安装App后依然有效,数据还在。
navigation 设置leftBarButtonItem 后,左滑返回失效:
self.navigationItem.leftBarButtonItem = deleteItem;
self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
社会化分享对比
Social :
SLServiceTypeTwitter
SLServiceTypeFacebook
SLServiceTypeSinaWeibo
SLServiceTypeTencentWeibo
SLServiceTypeLinkedIn
UIActivityViewController:
判断网络状态是2G/3G/4G
获取系统back 按钮事件
新版pod 须要设置target
platform :ios, ‘7.0‘
target "RWTFlickrSearch" do
pod ‘ReactiveCocoa‘, ‘2.1.8‘
pod ‘objectiveflickr‘, ‘2.0.4‘
pod ‘LinqToObjectiveC‘, ‘2.0.0‘
pod ‘SDWebImage‘, ‘3.6‘
end
storyboard textview 若是默认是中文,载入的时候会卡顿。
在视图哪里的时候别设置textview 中文
Xcode关于警告AutomaticPreferredMaxLayoutWidth的消除方法