touchesBegan开始编写一个应用代码前,首先应该列出事物清单(了解需要做什么)
从代码可移植性的角度来看,纯手写代码 > xib界面文件 > storyboard
从代码复杂度的角度来看,storyboard > xib 界面文件 > 纯手写代码
弹出提示框
[UIAlertView alloc]initWithTitle
iOS 8 建议使用 UIAlertController
http://blog.csdn.net/lengshengren/article/details/39896037
改变UIAlertController的标题、内容的字体和颜色
http://www.jianshu.com/p/51949eec2e9c
[UIView appearance].tintColor = [UIColor colorWithHexString:DSBlackColor];
可以统一修改按钮字体颜色。
分享功能实现:
UIActivityViewController
http://www.cocoachina.com/industry/20140425/8233.html
简单的系统 Loading效果 UIActivityIndicatorView
http://www.cnblogs.com/androidwsjisji/archive/2013/04/09/3009356.html
支持横屏
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之后
http://www.jianshu.com/p/b8b5deed5a8b
程序启动顺序:
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:
http://www.jianshu.com/p/d45656256aa9
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
NSString *URLString = [NSString stringWithFormat:@"%@/webservice/applyDaily",@"http://192.168.1.134:9000"];
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
http://www.cnblogs.com/thefeelingofsimple/p/IOS.html
在子线程中,界面的刷新、更新,一般要回到主线程中处理:
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];
http://www.jianshu.com/p/c59b32be2dfb  两个rect是否包含 交叉等。
触碰就收起键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];
}
http://www.cnblogs.com/gfxxbk/p/5575908.html 键盘类别 keyboardType
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内存泄漏
http://www.cocoachina.com/ios/20141203/10519.html
http://www.cocoachina.com/ios/20160222/15333.html
iOS应用如何实现64位的支持
http://www.open-open.com/lib/view/open1420697675843.html
http://www.codeceo.com/article/ios-64-bit.html
CocoaPods安装和使用教程
http://code4app.com/article/cocoapods-install-usage
https://cocoapods.org/
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];
}
gif动画实现:  http://blog.sina.com.cn/s/blog_983ef3f2010125tz.html
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 加进度条
https://github.com/JJSaccolo/UIActivityIndicator-for-SDWebImage
跑马灯效果 MarqueeLabel
https://github.com/cbpowell/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];
iOS 使用开源库 GTMBase64 转码http://www.2cto.com/kf/201405/297303.html
系统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];
清除缓存
http://www.open-open.com/lib/view/open1425625126743.html
缓存文件夹路径:
NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
AES加密
http://www.cnblogs.com/jys509/p/4768120.html
MD5 加密
http://www.jianshu.com/p/07c9023377d2
WKWebView iOS8 WebKit库之——WKWebView篇
http://blog.csdn.net/kilik52/article/details/39609657
http://blog.csdn.net/cyforce/article/details/37657009
关于wkwebview js交互用户
http://liuyanwei.jumppo.com/2015/10/17/ios-webView.html  
http://www.cnblogs.com/jiang-xiao-yan/p/5345893.html
(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,那么视图仍会延伸覆盖到四周的区域
使用NSLocalizedString实现国际化 http://blog.csdn.net/mamong/article/details/8510781
APP转让:http://blog.csdn.net/djxiaoyu_haha/article/details/40424479
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];
}
}];
}
}
2、在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
http://blog.csdn.net/ys410900345/article/details/42924641
http://blog.sina.com.cn/s/blog_74e9d98d01019vji.html
tableView视图下拉拉伸效果
http://www.jianshu.com/p/246d4f544968
3D touch
http://www.jianshu.com/p/898fd65e79ec
倒计时
MZTimerLabel https://github.com/mineschan/MZTimerLabel
获取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]   显示视图中的层级关系。
在不改变按钮尺寸的前提下,扩大按钮的点击范围
https://kevinmky.github.io/2015/12/17/%E6%89%A9%E5%A4%A7%E6%8C%89%E9%92%AE%E7%82%B9%E5%87%BB%E8%8C%83%E5%9B%B4/
textfield 的输入字数/不限制光标字数
http://www.jianshu.com/p/cf68b0c5e15e
生成二维码 http://blog.yourtion.com/custom-cifilter-qrcode-generator.html
绝对值:int abs(int i); // 处理int类型的取绝对值 double fabs(double i); //...float fabsf(float i); /
__FUNCTION__ 打印方法名
keyChain and TouchID
http://www.jianshu.com/p/fec5a3eb7ae4
通常情况下,我们用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
http://www.bubuko.com/infodetail-749763.html
http://www.jianshu.com/p/efcfa3c87306
获取系统back 按钮事件
http://blog.csdn.net/a330416020/article/details/41700821
新版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的消除方法
http://my.oschina.net/u/2340880/blog/657383

转载于:https://www.cnblogs.com/huayuan320/p/6278313.html

iOS开发项目实战狗粮相关推荐

  1. 视频教程-从零开发一个iOS企业级项目实战之我的云音乐视频 教程-iOS

    从零开发一个iOS企业级项目实战之我的云音乐视频 教程 任苹蜻,爱学啊创始人 & CEO,曾就职于某二车手公司担任Android工程师后离职创办爱学啊,我们的宗旨是:人生苦短,我们只做好课!熟 ...

  2. IOS开发-蓝牙实战项目-汪亮-专题视频课程

    IOS开发-蓝牙实战项目-4475人已学习 课程介绍         该视频面向有一定开发经验的IOS开发人员,视频主要通过实际上线项目,讲解蓝牙的搜索,连接,手机发送数据,手机接收数据,并处理返回的 ...

  3. python h5开发_从零搭建移动H5开发项目实战

    从零搭建移动H5开发项目实战 前端H5的前世今身 在Pc的时代,前端技术无疑统治了大多数用户的交互界面!而在移动为王的今天,NA开发在早期占领了大多数用户的交互界面,后来逐渐的前端H5开发找到了自己的 ...

  4. 从零搭建移动H5开发项目实战

    从零搭建移动H5开发项目实战 前端H5的前世今身 在Pc的时代,前端技术无疑统治了大多数用户的交互界面!而在移动为王的今天,NA开发在早期占领了大多数用户的交互界面,后来逐渐的前端H5开发找到了自己的 ...

  5. C# Xamarin For Android移动开发项目实战篇

    一.课程介绍 在前面阿笨的<C# Xamarin移动开发基础进修篇>课程中,大家已经熟悉和了解了Xamarin移动App开发的基础知识和原理.本次分享课<C# Xamarin移动开发 ...

  6. 视频教程-SpringBoot2+Vue+AntV前后端分离开发项目实战-Java

    SpringBoot2+Vue+AntV前后端分离开发项目实战 10多年互联网一线实战经验,现就职于大型知名互联网企业,架构师, 有丰富实战经验和企业面试经验:曾就职于某上市培训机构数年,独特的培训思 ...

  7. 视频教程-【三月】微信小程序云开发项目实战课程 - T3租机械-微信开发

    [三月]微信小程序云开发项目实战课程 - T3租机械 宁夏酷申科技有限公司技术总监,计算机专业毕业后一直从事技术开发和架构工作 袁永刚 ¥366.00 立即订阅 扫码下载「CSDN程序员学院APP」, ...

  8. Android游戏开发项目实战

    Android游戏开发项目实战: 手机游戏开发工程师培训教程(Android4.3.Cocos2d-x.Untity2D/3D.跨平台引擎技术) 课程讲师:厉风行 课程分类:游戏开发 适合人群:初级 ...

  9. (B站云e办)SpringBoot开发项目实战记录(七)(员工管理(分页知识))

    (B站云e办)SpringBoot开发项目实战记录(七) 一.员工管理 1.1 准备工作(分页配置类.日期格式化类) 1. mybatisplus配置类分页 2. 日期格式化类(converter) ...

  10. (B站云e办)SpringBoot开发项目实战记录(八)(Easy poi 完成excel导出导入)

    (B站云e办)SpringBoot开发项目实战记录(八) 一. pom依赖 二. 下载文件 2.1 jopo注释注解@Excel与@ExcelEntry 2.2 controller层 (完成exce ...

最新文章

  1. Science:中科院植物所马克平组揭示土壤真菌与树木密度的关系
  2. Mybatis中的jdbcType的作用
  3. A little something to get you started
  4. Java多线程学习三十三:Future 的主要功能是什么?
  5. windows启动linux系统,windows 10 启动linux系统
  6. java redis keys_jedis keys和scan操作
  7. Container with most water
  8. 编程趣谈_k++_++k_k一行顺序输出,结果会有差异吗?
  9. linux下磁盘及文件系统基础知识(1)
  10. 《如何让你爱的人爱上你》第一部分:第一印象
  11. 大一python题库及答案_Python经典题库及答案-python经典编程题
  12. 车型数据库设计 mongodb
  13. 20个BT下载网站,BT种子网站
  14. FIN断开-TCP segment of a reassembled PDU-原因分析
  15. newton插值公式
  16. pycharm调试bug Process finished with exit code -1073740791 (0xC0000409)
  17. html5 拖拽 编辑 插件,超给力 Vue.js 可视化H5拖拽编辑器Quark-H5
  18. 华为上机题之Word Maze(单词迷宫)
  19. 美国宾州计算机学校,美国留学,看看宾州有哪些顶尖学校?
  20. Android中模拟点击软件的实现原理探究

热门文章

  1. “室友靠这个拿到了华为50万年薪,太牛逼了…”
  2. frp穿透你的远程桌面
  3. 什么是数据分析,主要有什么目的,数据分析的处理流程是什么?
  4. 【BZOJ4484】【JSOI2015】最小表示(拓扑排序,bitset)
  5. 迈向智能世界2030的九大技术挑战与研究方向
  6. python全栈开发包括那些_什么是全栈工程师?有哪些知识?
  7. 【JAVASE】多线程编程基础
  8. 计算机画图讲课ppt,画图教学课件
  9. 安卓手机如何投屏到电视上_孩子在家上课,如何把手机投屏到电视上
  10. java分数计算_分数计算java