iOS开发中经常用到的代码块及技巧总结

1.cell中两种响应
1)点击button出现下拉菜单

//自定义cell中
@property(nonatomic,strong) UIImageView * bgView;
@property(nonatomic,strong) UIButton * controlButton;
       _bgView = [MyControl createImageViewWithFrame:CGRectMake(0, 60,       self.contentView.frame.size.width - 15, 60) imageName:@"下拉条-背景"];
 _bgView.hidden = YES;

 _bgView.tag = 9999;
 [self.contentView addSubview:_bgView];
    
    _controlButton = [MyControl createButtonFrame:CGRectMake(225, 20, 5, 20) bgImageName:nil image:@"圆点" title:nil method:nil target:self];
    [bigBgImageView addSubview:_controlButton];
//controller里边
        cell.controlButton.tag = 1000 + indexPath.row;
        cell.contentView.tag = 1000 + indexPath.row;

-(void)controlButtonClick:(UIButton *)button
{
    flag = button.tag - 1000;
    if (_tempView.superview.tag != button.tag) {
        _tempView.hidden = YES;
    }
    
    _tempView = [button.superview.superview viewWithTag:9999];
    [button.superview.superview viewWithTag:9999].hidden = ![button.superview.superview viewWithTag:9999].hidden;
    
    isHidden = [button.superview.superview viewWithTag:9999].hidden;
    
    //刷新界面
    [_tableView1 reloadData];
    
}

2)点击cell出现下拉菜单

cell.contentView.tag = 1000 + indexPath.row;
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        flag = indexPath.row;
        if (_tempView.superview.tag - 1000 != indexPath.row) {
            _tempView.hidden = YES;
        }
        
        _tempView = [[tableView cellForRowAtIndexPath:indexPath] viewWithTag:9999];
        
        [[tableView cellForRowAtIndexPath:indexPath] viewWithTag:9999].hidden = ![[tableView cellForRowAtIndexPath:indexPath] viewWithTag:9999].hidden;
        isHidden = [[tableView cellForRowAtIndexPath:indexPath] viewWithTag:9999].hidden;
        
        [_tableView1 reloadData];
    }

2.解决时差问题
//解决时差问题

NSDate * date = sender.date;
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: date];
NSDate *localeDate = [date  dateByAddingTimeInterval: interval];

//时差转化

NSDate *datenow = [NSDate date];//输出结果:2014-12-12 02:23:25 +0000晚八个小时
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate:datenow];
NSDate *localeDate = [datenow  dateByAddingTimeInterval: interval];//2014-12-12 10:23:25 +0000
NSLog(@"%@", localeDate);

//将秒数转化为日期格式

NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:1363948516];
NSLog(@"1363948516  = %@",confromTimesp);//2013-03-22 10:35:16 +0000

//将秒数转化为特定格式的日期格式

 NSString *str=@"1368082020"; //时间戳
NSTimeInterval time=[str doubleValue]+28800;//因为时差问题要加8小时 == 28800 sec
NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
NSLog(@"date:%@",[detaildate description]);
//实例化一个NSDateFormatter对象
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//设定时间格式,这里可以设置成自己需要的格式
[dateFormatter setDateFormat:@"yyyy-MM-dd"];

NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];

最终版本

NSString * startStr = [NSString stringWithFormat:@"%@",dic[@"startdate"]];
NSTimeInterval startTime = [startStr doubleValue] / 1000 + 28800;
NSDate * startLocalDate = [NSDate dateWithTimeIntervalSince1970:startTime];
NSDateFormatter * startFormatter = [[NSDateFormatter alloc]init];
[startFormatter setDateFormat:@"yyyy.MM.dd"];
NSString * startDate = [startFormatter stringFromDate:startLocalDate];

3.页面切换水波纹动画

DetailViewController * dvc = [[DetailViewController alloc]initWithSid:self.dataArray[indexPath.row][@"secid"] WithCollectorsCount:[self.dataArray[indexPath.row][@"collectcnt"] intValue]];
dvc.hidesBottomBarWhenPushed = YES;
CATransition*transition=[CATransition animation];
transition.duration=1.0f;
transition.type=@"rippleEffect";
transition.subtype=@"fromTop";
[self.navigationController.view.layer addAnimation:transition forKey:nil];
[self.navigationController pushViewController:dvc animated:YES];

4.去掉导航条和tabBar的边框

- (void)viewWillAppear:(BOOL)animated {
[self.navigationController.navigationBar setBackgroundImage:[TDUtils createImageWithColor:[UIColor clearColor]] forBarMetrics:UIBarMetricsDefault];
[self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:[TDUtils createImageWithColor:[UIColor clearColor]]];
[self.navigationController.navigationBar setShadowImage:[TDUtils createImageWithColor:[UIColor clearColor]]];
[self.tabBarController.tabBar setBackgroundImage:[TDUtils createImageWithColor:[UIColor clearColor]]];
[self.tabBarController.tabBar setShadowImage:[TDUtils createImageWithColor:[UIColor clearColor]]];

}

5。长按实现图标抖动和删除的代码例子

    - (void)wobble {
    static BOOL wobblesLeft = NO;
    if (isShake) {
    CGFloat rotation = (kWobbleRadians * M_PI) / 180.0;
    CGAffineTransform wobbleLeft = CGAffineTransformMakeRotation(rotation);
    CGAffineTransform wobbleRight = CGAffineTransformMakeRotation(-rotation);
    [UIView beginAnimations:nil context:nil];
    NSInteger i = 0;
    NSInteger nWobblyButtons = 0;
    //  for (NSArray* buttonPage in _buttons) {
    //  for (TTLauncherButton* button in buttonPage) {
    //  if (button != _dragButton) {
    //  ++nWobblyButtons;
        //  if (i % 2) {
          //    button.transform = wobblesLeft ? wobbleRight : wobbleLeft;
          //    } else {
        //  button.transform = wobblesLeft ? wobbleLeft : wobbleRight;
          //    }
        //  }
      //    ++i;
  //      }
//  }
for (UIView *tempView in [scrollView subviews]) {
if ([tempView isKindOfClass:[TestView class]] || [tempView isKindOfClass:[UIButton class]]) {
++nWobblyButtons;
if (i % 2) {
tempView.transform = wobblesLeft ? wobbleRight : wobbleLeft;
} else {
tempView.transform = wobblesLeft ? wobbleLeft : wobbleRight;
}
++i;
}
}
if (nWobblyButtons >= 1) {
[UIView setAnimationDuration:kWobbleTime];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(wobble)];
wobblesLeft = !wobblesLeft;
} else {
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[self performSelector:@selector(wobble) withObject:nil afterDelay:kWobbleTime];
}
[UIView commitAnimations];
}
}

- (void)startTimer {
isShake = YES;
if (shakeViewTimer == nil) {
shakeViewTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self
selector:@selector(wobble) userInfo:nil repeats:NO];
}
}

- (void)stopShake {
isShake = NO;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3f];
//  [UIView setAnimationDelegate:self];
for (UIView *tempView in [scrollView subviews]) {
tempView.transform = CGAffineTransformIdentity;
}
[UIView commitAnimations];
for (UIView *tempView in [scrollView subviews]) {
if ([tempView isKindOfClass:[UIButton class]]) {
[tempView removeFromSuperview];
}
}
}

6.导航条有多按钮时的用法
UIBarButtonItem 工具栏按钮有3种主要的定制方法:

  • 1、在Interface builder中定制;
  • 2、setItems方法定制;
  • 3、addSubview方法定制。
UIBarButtonItem * clearnButton = [UIBarButtonItem alloc] initWithTitle:@"Code" style:UIBarButtonItemStyleBordered target:self action:@selector(code)];    初始化

NSArray *buttonArray = [[NSArray alloc]initWithObjects:cleanButton,saveButton, nil];
self.navigationItem.rightBarButtonItems = buttonArray; 多按钮用法

7.真机测试时出现的问题

No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=armv7, VA

运行报错

出现的原因:armv7s是应用在iPhone 5 A6 的架构上的
解决的方式:
1,在Project target里“Architectures”设置为“Standard (armv7,armv7s)”
2,修改在Project target里“Build Settings”的“Valid Architectures”添加“i386”和“armv7”(Xcode4.6 以上版本不再支持armv6,请去掉)
3,设置”Build Active Architecture Only”为“NO”。这样你build你的项目的时候就能在iphoe5和iphoe4s里执行。

armv6, armv7, armv7s的区别

8.datepicker修改为中文

//方法一
[datePicker setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];

方法二
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];//设置为中文显示3
_datePicker.locale = locale;

9.进制颜色转换成RGB

-(UIColor*)changeColor:(NSString*)colorString
{
    CGFloat alpha,red,green,blue;
    //alpha=[self colorComponentFrom:colorString start:0 length:2];
    red=[self colorComponentFrom:colorString start:0 length:2];
    green=[self colorComponentFrom:colorString start:2 length:2];
    blue=[self colorComponentFrom:colorString start:4 length:2];
    
    return [UIColor colorWithRed:red green:green blue:blue alpha:1];
}
- (CGFloat) colorComponentFrom:(NSString*)string start:(NSUInteger)start length:(NSUInteger)length
{
    NSString *substring = [string substringWithRange: NSMakeRange(start, length)];
    NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];
    unsigned hexComponent;
    [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];
    return hexComponent/255.0;
}

10.UIView的相关不常用属性

//设置自动适配模式
imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight| UIViewAutoresizingFlexibleWidth;
 //设置停靠模式
imageView.contentMode = UIViewContentModeScaleAspectFill;

11.屏幕不允许旋转的方法是什么?

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}

12.电池状态栏改变颜色

//方法一:不用修改plist
 [self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];

//默认的黑色(UIStatusBarStyleDefault)
//白色(UIStatusBarStyleLightContent)

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
//方法二:需要修改plist
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];

//设置状态栏字体颜色中国移动的颜色改为白色(需要设置plist文件里的View controller-based status bar appearance属性为NO;)
    [UIApplication sharedApplication].statusBarStyle=UIStatusBarStyleLightContent;
//隐藏项目中得状态栏
 [[UIApplication sharedApplication]setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
//info.plist文件中Status bar is initially hidden   yes
View controller-based status bar appearance   NO

13.SVN上传文件时.a文件缺失时的解决办法
svn import后,服务器上少了所有.a文件的问题解决
将本地代码import到svn服务器。
svn co出代码,编译却报错少了这个那个
.a文件,手动添加这些*.a文件极其麻烦。
*.a文件丢失的原因:
svn有个默认的global-ignores列表,会忽略那些不常用的文件,如:
*.o *.lo *.la *.al .libs *.so .so.[0-9] *.pyc .pyo
.rej ~ ## .# .
.swp .DS_Store等。
打开~/ .subversion/config 文件看到被注释的下面2行
#global-ignores = *.o *.lo *.la *.al .libs *.so .so.[0-9] *.a *.pyc .pyo
# .rej ~ ## .# .
.swp .DS_Store
说明svn就是启用默认的global-ignores列表
解决办法:

global-ignores = *.o *.lo *.la *.al .libs *.so *.so.[0-9]* *.pyc *.pyo
*.rej *~ #*# .#* .*.swp .DS_Store

启用被注释的这2行(注意global之前不能有空格, 被忽略的文件格式之前是一个空格,不能多否则执行svn命令如svn info报错

svn: /Users/gavinhuang/.subversion/config:94: Option expected)

修改后再import就不会丢失*.a文件了

global-ignores = *.o *.lo *.la *.al .libs *.so *.so.[0-9]* *.a *.pyc *.pyo
#  *.rej *~ #*# .#* .*.swp .DS_Store
改成
global-ignores =  *.lo *.la *.al .libs *.so *.so.[0-9]*  *.pyc *.pyo
#   *.rej *~ #*# .#* .*.swp .DS_Store

14.UISearchDisplayController 是苹果专为 UITableView 搜索封装的一个类,NavigationBar 当点击搜索框时 TableView 会自动弹上去覆盖
NavigationBar,达到一种全屏搜索的效果
http://www.cnblogs.com/lesliefang/p/3929677.html

16.**iOS XMPP****怎么实现语音聊天
**
**解决方案****1****:
两种处理方式
1、将获取到的音频文件通过base64加密直接通过xmpp的消息体发送过去,然后解码;
2、通过http请求的方式将音频文件上传到服务器,然后将音频文件的下载地址通过xmpp消息体发送过去,另外一个客户端下载。音频文件建议转码为amr,这种格式的音频文件比较小。
方法一的具体方法是什么, 我是把wav转化为amr然后再通过base64处理,可是再解码成wav时候,文件出现错误

17.通过抖动的方式提示用户textField文本输入框的text值为空或错误

    1.  //TextField的晃动:Begin  
    2.  @interface UITextField(shake)  
    3.    
    4.  - (void)shake;  
    5.    
    6.  @end  
    7.    
    8.  @implementation UITextField(shake)  
    9.    
    10. - (void)shake  
    11. {  
    12.     CAKeyframeAnimation *animationKey = [CAKeyframeAnimationanimationWithKeyPath:@"position"];  
    13.     [animationKey setDuration:0.5f];  
    14.       
    15.     NSArray *array = [[NSArrayalloc] initWithObjects:  
    16.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x, self.center.y)],  
    17.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],  
    18.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],  
    19.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x, self.center.y)],  
    20.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],  
    21.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],  
    22.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x, self.center.y)],  
    23.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],  
    24.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],  
    25.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x, self.center.y)],  
    26.                       nil];  
    27.     [animationKey setValues:array];  
    28.     [array release];  
    29.       
    30.     NSArray *times = [[NSArrayalloc] initWithObjects:  
    31.                       [NSNumbernumberWithFloat:0.1f],  
    32.                       [NSNumbernumberWithFloat:0.2f],  
    33.                       [NSNumbernumberWithFloat:0.3f],  
    34.                       [NSNumbernumberWithFloat:0.4f],  
    35.                       [NSNumbernumberWithFloat:0.5f],  
    36.                       [NSNumbernumberWithFloat:0.6f],  
    37.                       [NSNumbernumberWithFloat:0.7f],  
    38.                       [NSNumbernumberWithFloat:0.8f],  
    39.                       [NSNumbernumberWithFloat:0.9f],  
    40.                       [NSNumbernumberWithFloat:1.0f],  
    41.                       nil];  
    42.     [animationKey setKeyTimes:times];  
    43.     [times release];  
    44.       
    45.     [self.layeraddAnimation:animationKey forKey:@"TextFieldShake"];  
    46. }  
    47.   
    48. @end  
    49. //TextField的晃动:End 

18.程序退出,window界面变成黑色

  [UIView animateWithDuration:10.0f animations:^{
                    window.alpha = 0;

                } completion:^(BOOL finished) {
                    exit(0);
                }];
  1. 动态的计算label和imageVIew的高度
+(CGFloat)heightWithData:(NSDictionary*)dic
{
    static TableViewCell * cell = nil;
    if (cell == nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"TableViewCell" owner:nil options:nil] objectAtIndex:0];
    }
    
    //取label尺寸
    CGRect textRect = cell.text.frame;
    CGRect labelRect = [dic[@"text"] boundingRectWithSize:CGSizeMake(textRect.size.width, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:[NSDictionary dictionaryWithObjectsAndKeys:cell.text.font,NSFontAttributeName, nil] context:nil];
    //取照片尺寸
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:dic[@"url"]]];
    CGFloat imageHeight =  [UIImage imageWithData:data].size.height*cell.urlImage.frame.size.width/[UIImage imageWithData:data].size.width;
    return (cell.frame.size.height - cell.text.frame.size.height - cell.urlImage.frame.size.height + labelRect.size.height + imageHeight);

}

//根据文字多少计算大小

 size = [str boundingRectWithSize:CGSizeMake(200, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:10]} context:nil].size;

21.二维码图片中间添加logo

+(UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2
{
    UIGraphicsBeginImageContext(image1.size);

    //Draw image1
    [image1 drawInRect:CGRectMake(0, 0, image1.size.width, image1.size.height)];
    
    //Draw image2
    
    [image2 drawInRect:CGRectMake((image1.size.width - 60)/ 2, (image1.size.height - 60)/2, 60, 60)];
    
    UIImage *resultImage=UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return resultImage;
}

22.定义枚举的几种方法

//方法一
typedef NS_ENUM(NSInteger, enumCellButtonIndex)
{
    eCBIFirst,
    eCBISecond,
};
//方法二
typedef enum {
    
    commonTag,
    differentTag,
    noCommonTag
    
}SortedTag;
//方法三
typedef enum : NSUInteger {
    eQDTabViewTypeTop,
    eQDTabViewTypeBottom,
    eQDTabViewTypeBottomHideBar
} QDTabViewType;

23.KVO解决特殊字段(与关键词一样的敏感词)

-(void)setValue:(id)value forUndefinedKey:(NSString *)key 
{ 
    if ([key isEqualToString:@"id"]) { 

        self.ID = value; 
      } 
} 

24,类似通讯录大字母提示功能

#pragma mark - 创建动画标题

-(void)createBigLabel
{
    UILabel * bigLabel = [MyControl createLableFrame:CGRectMake(0, 0, 50, 50) font:30 title:@""];
    bigLabel.backgroundColor = [UIColor clearColor];
    bigLabel.textColor = [UIColor whiteColor];
    bigLabel.textAlignment = NSTextAlignmentCenter;
    //设置bigLabel在正中间
    bigLabel.center = CGPointMake(MRScreenWidth / 2, MRScreenHeight / 2 - 50);
    //削圆
    bigLabel.layer.cornerRadius = 5;
    bigLabel.layer.masksToBounds = YES;
    [self.view addSubview:bigLabel];
    self.bigLabel = bigLabel;
}

#pragma mark - tableView的代理方法

//使跳到被点击的section位置
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    title = [_keys objectAtIndex:index];
    
    //在主线程中实现动画效果
    //dispatch_async(dispatch_get_main_queue(), ^{
    
    [self.bigLabel.layer removeAnimationForKey:@"animateOpacity"];
    CABasicAnimation * theAnimation;
    theAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    theAnimation.duration = 2.0;
    theAnimation.fromValue = [NSNumber numberWithFloat:1.0];
    theAnimation.toValue = [NSNumber numberWithFloat:0.0];
    theAnimation.fillMode = kCAFillModeBoth;
    theAnimation.removedOnCompletion = NO;
    //theAnimation.delegate = self;
    [self.bigLabel.layer addAnimation:theAnimation forKey:@"animateOpacity"];
    
    //为bigLabel添加文字
    self.bigLabel.text = title;
    self.bigLabel.backgroundColor = [UIColor colorWithRed:64 / 255.0 green:113 / 255.0 blue:147 / 255.0 alpha:1];
    //});
    return index;
}
//设置右边的索引按钮
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    //右边的a-z
    return _keys;
}
//类似参考方法 
CALayer* layer = _SaveView.layer;
    anim = [CABasicAnimation animationWithKeyPath:@"opacity"];
    anim.fromValue = @1.0;
    anim.toValue = @0.0;
    anim.autoreverses = YES;
    anim.repeatCount = INFINITY;
    anim.duration = 2.0;
    [layer addAnimation:anim forKey:@"anim"];

25.设置label的行间距

+ (NSAttributedString *)setLineSpacing:(int)lineSpace font:(UIFont*)font foreColor:(UIColor*)foreColor withString:(NSString *)str
{
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    [paragraphStyle setLineSpacing:lineSpace];
    NSDictionary * attributes = @{NSFontAttributeName:font,NSParagraphStyleAttributeName:paragraphStyle,NSForegroundColorAttributeName:foreColor};
    NSAttributedString * attributedString = [[NSAttributedString alloc]initWithString:str attributes:attributes];
    return attributedString;
    
}

获取控件高度
+ (CGFloat)getHeightByText:(NSString *)text textFont:(UIFont *)font lineSpacing:(int)lineSpacing sizeWidth:(CGFloat)width
{

    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    [paragraphStyle setLineSpacing:lineSpacing];
    NSDictionary * attributes = @{NSFontAttributeName:font,NSParagraphStyleAttributeName:paragraphStyle,NSForegroundColorAttributeName:[UIColor blackColor]};
    
    CGRect labelRect = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:attributes context:nil];
    
    return labelRect.size.height;
}

26.popToViewController的用法

 NSArray *arr=self.navigationController.viewControllers;
    int i= arr.count-(arr.count-2);
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:i] animated:YES];

27.适配iphone6和iphone6 plus的宏定义

//iphone6 plus

#define iPhone6p ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242,2208), [[UIScreen mainScreen] currentMode].size) : NO)

//iphone6
#define iPhone6 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) : NO)


//iphone四个版本适配
#define iPhone4 CGSizeEqualToSize([UIScreen mainScreen].bounds.size,CGSizeMake(320, 480))
#define iPhone5 CGSizeEqualToSize([UIScreen mainScreen].bounds.size,CGSizeMake(320, 568))
#define iPhone6 CGSizeEqualToSize([UIScreen mainScreen].bounds.size,CGSizeMake(375, 667))
#define iPhone6plus CGSizeEqualToSize([UIScreen mainScreen].bounds.size,CGSizeMake(414, 736))

28.TabBar上添加消息提示小红点

  1. 如果有数字,直接使用 viewController.tabBarItem.badgeValue = @"1";
  1. 没有数字,自己往tabbar加subView。
    需要注意的是坐标x,y一定要是整数,否则会有模糊。
    UIImageView *dotImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"personinfo_unread@2x.png"]];
    dotImage.backgroundColor = [UIColor clearColor];
    dotImage.tag = RED_DOT_TAG;
    CGRect tabFrame = tabbarController.tabBar.frame;
    CGFloat x = ceilf(0.94 * tabFrame.size.width);
    CGFloat y = ceilf(0.2 * tabFrame.size.height);
    dotImage.frame = CGRectMake(x, y, 6, 6);
    [tabbarController.tabBar addSubview:dotImage];
    [dotImage release];

29.读取数据库sqlite中的内容

-(void)loadData
{
    //使用数据库
    NSString * path = [[NSBundle mainBundle]pathForResource:@"asd.sqlite3" ofType:@"db"];
    NSLog(@"数据库路径~~~%@",path);
    
    _fmDataBase = [FMDatabase databaseWithPath:path];
    
    if ([_fmDataBase open])
    {
        NSLog(@"打开成功");
    }
    else
    {
        NSLog(@"打开失败");
    }
    
    //数据库打开成功,查询职位类别相关数据
    FMResultSet * jobCategoryMasterResult = [_fmDataBase executeQuery:@"select * from t_o_org_jobcategory_master"];
    self.jobCategory_masterDataArray = [NSMutableArray arrayWithCapacity:0];
    while ([jobCategoryMasterResult next])
    {
        NSString * idStr = [jobCategoryMasterResult stringForColumn:@"id"];
        NSString * nameStr = [jobCategoryMasterResult stringForColumn:@"name"];
        NSString * statusStr = [jobCategoryMasterResult stringForColumn:@"status"];
        
        //创建一个临时数组
        NSArray * tempArray = @[idStr,nameStr,statusStr];
        [self.jobCategory_masterDataArray addObject:tempArray];
    }
    
    NSLog(@"职位类别~~~%@",self.jobCategory_masterDataArray);
    
}

30.自动布局之autoresizingMask使用详解(Storyboard&Code)
http://www.cocoachina.com/ios/20141216/10652.html

31.如何添加Launch Image

1.删掉launch.xib
2.genera -》 launch images source 改为LaunchImage
3.info 删掉 launch screen file

launch.xib是iOS8后才加载的 iOS7或者6不加载 所以适用性不高


32.给图片添加毛玻璃效果

CALayer* _bg_layer = [CALayer layer];
    _bg_layer.frame = checkView.bgImageV.frame;
    [checkView.bgImageV.layer addSublayer:_bg_layer];
    
    //float scale = [UIScreen mainScreen].scale;
    UIGraphicsBeginImageContextWithOptions(checkView.bgImageV.frame.size, YES, 1);
    [del.window drawViewHierarchyInRect:CGRectMake(0, 0, del.window.frame.size.width, del.window.frame.size.height) afterScreenUpdates:NO];
    __block UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //裁剪图片
    CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, CGRectMake(_bg_layer.frame.origin.x * 1, _bg_layer.frame.origin.y * 1, _bg_layer.frame.size.width * 1, _bg_layer.frame.size.height * 1));
    image = [UIImage imageWithCGImage:imageRef];
    
    //添加效果
    image = [image applyBlurWithRadius:5.0f tintColor:[UIColor colorWithRed:238 green:238 blue:235 alpha:0.1] saturationDeltaFactor:2 maskImage:nil];
    
    _bg_layer.contents = (__bridge id)(image.CGImage);

33.让程序在后台较长久的运行

// AppDelegate.h文件
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;

// AppDelegate.m文件
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [self beingBackgroundUpdateTask];
    // 在这里加上你需要长久运行的代码
    [self endBackgroundUpdateTask];
}

- (void)beingBackgroundUpdateTask
{
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}

- (void)endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;

34.几种小的概念和方法

1、sleep
[NSThread sleepForTimeInterval:4];
2、活动指示器控件
UIActivityIndicatorView
3、 _cmd的使用
_cmd是iOS内置变量,始终指向当前方法的selector
4、状态加入事件通知中心
[center addObserver:self selector:@selector(applicationWillResignActive)        name:UIApplicationWillResignActiveNotification  object:nil];
5、用NSUserDefault保存用户数据
  使用方法:  
      保存:
      NSInteger selectedIndex = self.segmentedControl.selectedSegmentIndex;          [[NSUserDefaults standardUserDefaults] setInteger:selectedIndex          forKey:@"selectedIndex"];
      取出:
      NSNumber *indexNumber = indexNumber = [[NSUserDefaults standardUserDefaults]          objectForKey:@"selectedIndex"];          if (indexNumber) {           NSInteger selectedIndex = [indexNumber intValue];           self.segmentedControl.selectedSegmentIndex = selectedIndex;}

35.解决base64 冲突
删除掉 Other Linker Flag 的 -all_load 就可以解决静态库冲突的问题

36.有三种方式可以引入静态库文件
第一种方式:直接将对应平台的.a文件拖拽至Xcode工程左侧的Groups&Files中,缺点是每次在真机和模拟器编译时都需要重新添加.a文件;
第二种方式:使用lipo命令将设备和模拟器的.a合并成一个通用的.a文件,将合并后的通用.a文件拖拽至工程中即可,具体命令如下

lipo -create Release-iphoneos/libbaidumapapi.a Release-iphonesimulator/libbaidumapapi.a -output libbaidumapapi.a

第三种方式:

  1. 将API的libs文件夹拷贝到您的Application工程根目录下
  2. 在Xcode的Project -> Edit Active Target -> Build -> Linking -> Other Linker Flags中添加-ObjC
  3. 设置静态库的链接路径,在Xcode的Project -> Edit Active Target -> Build -> Search Path -> Library Search Paths中添加您的静态库目录,比如"$(SRCROOT)/../libs/Release$(EFFECTIVE_PLATFORM_NAME)"$(SRCROOT)宏代表您的工程文件目录,$(EFFECTIVE_PLATFORM_NAME)宏代表当前配置是OS还是simulator
    注:静态库中采用ObjectC++实现,因此需要您保证您工程中至少有一个.mm后缀的源文件(您可以将任意一个.m后缀的文件改名为.mm),或者在工程属性中指定编译方式,即将Xcode的Project -> Edit Active Target -> Build -> GCC4.2 - Language -> Compile Sources As设置为"Objective-C++"
    37.GPS定位不准确,我们可以用地图定位和代替,简单误差小
#pragma mark - 获取经纬度和城市
-(void)getCurrentLocation
{
    _mapView = [[MAMapViewalloc] init];
    [_mapView setHidden:YES];
    _mapView.showsUserLocation =YES;
    _mapView.delegate = self;
}
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation {
    _currentLocation = userLocation.location;
    _lon = _currentLocation.coordinate.longitude;
    _lat = _currentLocation.coordinate.latitude;
    _tableObject_dis.lon = _lon;
    _tableObject_dis.lat = _lat;
    _placemark  = nil;
    if ([[[UIDevicecurrentDevice] systemVersion]floatValue] >= 5.0) {
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        [geocoder reverseGeocodeLocation:_currentLocation completionHandler:^(NSArray *placemarks, NSError*error){
            if (!error)
            {
                _placemark = [placemarks objectAtIndex:0];
                if (_placemark.administrativeArea)
                {
                    NSArray *stateName = [_placemark.administrativeArea componentsSeparatedByString:@"市"];
                    _currentState =[stateName objectAtIndex:0] ;
                    mapView.showsUserLocation = NO;
                }
            }
        }];
        [geocoder release];
    }
}

40.获取手机验证码

-(void)sendYanzhengma:(UIButton*)sender
{
    [self huoQuYanZhengMa];//这个函数是和服务器交互获取服务器返回的验证码
    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changText:) userInfo:nil repeats:YES];
    NSLog(@"%@",timer.description);
}

//定时器的响应函数实现
-(void)changText:(NSTimer*)sender
{
    count--;
    [sendBtn setTitle:[NSString stringWithFormat:@"(%d)秒后重新获取",count] forState:UIControlStateNormal];
    sendBtn.userInteractionEnabled = NO;
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    if (count == 0) {
        count = 60;
        [sendBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        sendBtn.userInteractionEnabled = YES;
        sendBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        [sender invalidate];
    }
    
}

45.计算文字的高度和宽度(自适应)

- (id)initWithLabelSize:(CGSize)labelSize textContent:(NSString *)textContent font:(UIFont *)font
{
    self = [super init];
    if (self) {
        if(textContent==nil){
            textContent=@" ";
        }
        CGSize lblSize = CGSizeMake(labelSize.width, 4000.0f);
        NSDictionary *attribute = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
        NSAttributedString *attributeString = [[NSAttributedString alloc] initWithString:textContent attributes:attribute];
        CGRect rect = [attributeString boundingRectWithSize:lblSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
        _labelFrame = rect;
    }
    return self;
}

46工程文件中出现的问题
1、代码中 某文件后面有 “M” 标记,表示该文件已被修改,需要 commit.
(右键该文件 -> source control -> commit selected file...)
2、代码中 某文件后面有 “A” 标记,表示该文件是新添加的,已受SVN管理,需要 commit.
(右键该文件 -> source control -> commit selected file...)
3、代码中 某文件后面有 “?” 标记,表示该文件是新添加的,并且脱离了SVN的管理,首先需要add,然后 commit.
(右键该文件 -> source control -> Add,这样该文件的标记就变为 “A”,然后在 commit)
4、代码中 某文件后面有 “D” 标记,表示该文件在服务器上已被删除,这时update的话,可删除本地的文件。
5、代码中 某文件后面有 “C” 标记,表示该文件与服务器的文件冲突。
48.网络请求获取单张图片

-(UIImage *) getImageFromURL:(NSString *)fileURL {
    SDImageCache *cache = [SDImageCache sharedImageCache];
    if ([cache imageFromDiskCacheForKey:fileURL] || [cache imageFromMemoryCacheForKey:fileURL]) {
        UIImage *image = [cache imageFromDiskCacheForKey:fileURL]?[cache imageFromDiskCacheForKey:fileURL]:[cache imageFromMemoryCacheForKey:fileURL];
        return image;
    }else{
    NSLog(@"执行图片下载函数");
    UIImage * result;
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    result = [UIImage imageWithData:data];
    [cache storeImage:result forKey:fileURL];
    return result;
    }
}

49.友盟分享
AppDelegate中

//友盟分享
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "UMSocialSinaHandler.h"
#import "UMSocialSinaSSOHandler.h"
#import "WXApi.h"
#import "ShareToPersonViewController.h"

//友盟分享,注册友盟,APPKEY:559f2b4d67e58ef8c5006bd5
    [UMSocialData setAppKey:[NSString stringWithFormat:@"%@",UMSHAREAPPKEY]];
    //设置微信AppId,设置分享url,默认使用友盟的网址
    
    [UMSocialQQHandler setQQWithAppId:@"1104683143" appKey:@"twRf0aK41nspT2Im" url:@""];
    [UMSocialQQHandler setSupportWebView:YES];
    
    [UMSocialWechatHandler setWXAppId:@"wx12b8d929be7d2a97" appSecret:@"12e4f8411174002f3a95d6cbf51b69d8" url:@""];
    
    //打开新浪微博的SSO开关
    [UMSocialSinaHandler openSSOWithRedirectURL:@"http://open.weibo.com/apps/"];
    
    //设置隐藏未安装客户端的情况
    //微信未安装
   if (![WXApi isWXAppInstalled]) {
        [UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToWechatSession,UMShareToWechatTimeline]];
   }
    //添加自定义分享按钮
    UMSocialSnsPlatform *snsPlatform = [[UMSocialSnsPlatform alloc] initWithPlatformName:@"CustomPlatform"];
    snsPlatform.displayName = @"风游精好友";
    snsPlatform.bigImageName = @"share-friend-icon.png";
    snsPlatform.snsClickHandler = ^(UIViewController *presentingController, UMSocialControllerService * socialControllerService, BOOL isPresentInController){
        NSLog(@"点击自定义平台的响应");
        ShareToPersonViewController * vc = [[ShareToPersonViewController alloc]init];
        [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
    };
    [UMSocialConfig addSocialSnsPlatform:@[snsPlatform]];
    //设置要在分享面板中出现的平台
    [UMSocialConfig setSnsPlatformNames:@[@"CustomPlatform",UMShareToQQ,UMShareToQzone,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToSina]];

     分享按钮响应函数

- (void)shareClick:(UIButton *)sender{
    
    NSString * imageString = _model.imgArray[0];
    __weak DetailZaiViewController * weakSelf = self;
    [UMSocialSnsService presentSnsIconSheetView:self appKey:[NSString stringWithFormat:@"%@",UMSHAREAPPKEY] shareText:[NSString stringWithFormat:SHARECONTENTWORDURL,_model.contentId] shareImage:[UIImage imageNamed:@"logo-group.png"] shareToSnsNames:@[UMShareToQQ, UMShareToQzone, UMShareToWechatSession, UMShareToWechatTimeline, UMShareToSina] delegate:weakSelf];
    [UMSocialData defaultData].extConfig.qqData.url = [NSString stringWithFormat:SHARECONTENTURL,_model.contentId];
    [UMSocialData defaultData].extConfig.qzoneData.url = [NSString stringWithFormat:SHARECONTENTURL,_model.contentId];
    [UMSocialData defaultData].extConfig.wechatSessionData.url = [NSString stringWithFormat:SHARECONTENTURL,_model.contentId];
    [UMSocialData defaultData].extConfig.wechatTimelineData.url =  [NSString stringWithFormat:SHARECONTENTURL,_model.contentId];
}

50.沙河目录
Documents放不可再生的配置文件Library放可再生的数据文件temp文件夹在系统内存不够或者关机开机的时候会自动清除
NSString *path = NSHomeDirectory();

上面的代码得到的是应用程序目录的路径,在该目录下有三个文件夹:Documents、Library、temp以及一个.app包!

该目录下就是应用程序的沙盒,应用程序只能访问该目录下的文件夹!!!
1、

NSString *path1 = NSHomeDirectory();
NSLog(@"path1:%@", path1);path1:/Users/yuanjun/Library/Application Support/iPhone Simulator/4.2/Applications/172DB70A-145B-4575-A31E-D501AC6EA830

2、

NSString *path2 = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSLog(@"path2:%@", path2);path2:/Users/yuanjun/Library/Application Support/iPhone Simulator/4.2/Applications/172DB70A-145B-4575-A31E-D501AC6EA830/Library/Caches

3、

NSString *path3 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

NSLog(@"path3:%@", path3);path3:/Users/yuanjun/Library/Application Support/iPhone Simulator/4.2/Applications/172DB70A-145B-4575-A31E-D501AC6EA830/Documents

4、

NSString *path4 = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

NSLog(@"path4:%@", path4);path4:/Users/yuanjun/Library/Application Support/iPhone Simulator/4.2/Applications/172DB70A-145B-4575-A31E-D501AC6EA830/Documents

5、

NSString *path5 = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];

NSLog(@"path5:%@", path5);path5:/Users/yuanjun/Library/Application Support/iPhone Simulator/4.2/Applications/172DB70A-145B-4575-A31E-D501AC6EA830/Library

6、

NSString *path6 = [NSHomeDirectory() stringByAppendingPathComponent:@"temp"];

NSLog(@"path6:%@", path6);path6:/Users/yuanjun/Library/Application Support/iPhone Simulator/4.2/Applications/172DB70A-145B-4575-A31E-D501AC6EA830/temp

51.SDWebImage清除缓存
清除缓存:

[[SDImageCache sharedImageCache] clearDisk];
[[SDImageCache sharedImageCache] clearMemory];

52.视频的边下载边播放
原理是这样的: 在iOS本地开启Local Server服务,然后 MPMoviePlayerController 请求本地Local Server服务。本地Local Server服务再不停的去对应的视频地址获取视频流。本地Local Server请求的时候,就可以把视频流缓存在本地。
53、iOS APP的启动过程
App通过UIApplicationMain进入,根据Info.plist里的信息执行初始化(如果有Storyboard则加载),随后执行

  • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

中的内容 ,执行完毕后,进行界面绘制,最后启动完毕,进入事件等待循环。
暂时写这么多,等有时间再继续写。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容