iOS-经常使用开发代码

1.打印继承关系 ios

po [self recursiveDescription]数组

<MySearchBar: 0x12c61c990; baseClass = UISearchBar; frame = (0 0; 320 44); text = ''; gestureRecognizers = <NSArray: 0x17405a700>; layer = <CALayer: 0x1740391e0>>
   | <UIView: 0x1741922e0; frame = (0 0; 320 44); clipsToBounds = YES; autoresize = W+H; layer = <CALayer: 0x1740392a0>>
   |    | <UISearchBarBackground: 0x12c61d450; frame = (0 0; 320 44); opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x1740392e0>>
   |    | <UISearchBarTextField: 0x12c624880; frame = (0 0; 0 0); text = ''; clipsToBounds = YES; opaque = NO; gestureRecognizers = <NSArray: 0x17405e600>; layer = <CALayer: 0x17403bdc0>>缓存

   |    |    | <_UISearchBarSearchFieldBackgroundView: 0x12c624c70; frame = (0 0; 0 0); opaque = NO; autoresize = W+H; userInteractionEnabled = NO; layer = <CALayer: 0x17403cba0>>安全

 

2.系统设置导航栏左滑退出app

    // 设置系统左滑退出
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;iphone

    self.navigationController.interactivePopGestureRecognizer.delegate = self;ide

3.拉伸图片函数

UIEdgeInsets edge1=UIEdgeInsetsMake(10, 10, 10, 10);
    UIImage *btnImage = [UIImage imageNamed:@"anhaoFour_departmentBackground"];
    btnImage = [btnImage resizableImageWithCapInsets:edge1 resizingMode:UIImageResizingModeTile];post

    [nearPeerCell.departmentBtn setBackgroundImage:btnImage forState:UIControlStateNormal];字体

4.NS_ENUM

  

5.屏幕尺寸

iphone4,4s === 3.5寸 === 960X640

iphone5,5s === 4.0寸 === 1136X640

iphone6    === 4.7寸 === 1334X750

iphone6+   === 5.5寸 === 2208X1242

 

ipad1      === 9.7寸 === 1024X768

ipad2      === 9.7寸 === 1024X768

The New iPad(Retina)=== 9.7寸 === 2048X1536

ipad4      === 9.7寸 === 2048X1536

 

ipad mini1 === 7.9寸 === 1024X768

ipad mini2 === 7.9寸 === 2048X1536

ipad mini2 === 7.9寸 === 2048X1536

 

6.UIView autoresizingMask

  若是视图的autoresizesSubviews属性声明被设置为YES,则其子视图会根据autoresizingMask属性的值自动进行尺寸调整。简单配置一下视图的自动尺寸调整掩码经常就能使应用程序获得合适的行为;不然,应用程序就必须经过重载layoutSubviews方法来提供本身的实现。
  self.autoresizingMask = UIViewAutoresizingFlexibleWidth;//这个常量若是被设置,视图的宽度将和父视图的宽度一块儿成比例变化。不然,视图的宽度将保持不变。
  
UIViewAutoresizingNone
这个常量若是被设置,视图将不进行自动尺寸调整。
UIViewAutoresizingFlexibleHeight
这个常量若是被设置,视图的高度将和父视图的高度一块儿成比例变化。不然,视图的高度将保持不变。
UIViewAutoresizingFlexibleWidth
这个常量若是被设置,视图的宽度将和父视图的宽度一块儿成比例变化。不然,视图的宽度将保持不变。
UIViewAutoresizingFlexibleLeftMargin
这个常量若是被设置,视图的左边界将随着父视图宽度的变化而按比例进行调整。不然,视图和其父视图的左边界的相对位置将保持不变。
UIViewAutoresizingFlexibleRightMargin
这个常量若是被设置,视图的右边界将随着父视图宽度的变化而按比例进行调整。不然,视图和其父视图的右边界的相对位置将保持不变。
UIViewAutoresizingFlexibleBottomMargin
这个常量若是被设置,视图的底边界将随着父视图高度的变化而按比例进行调整。不然,视图和其父视图的底边界的相对位置将保持不变。
UIViewAutoresizingFlexibleTopMargin

这个常量若是被设置,视图的上边界将随着父视图高度的变化而按比例进行调整。不然,视图和其父视图的上边界的相对位置将保持不变。

 

7.NSArray NSDictionary

 

    NSArray *array = @[@"",@"",@""];
    NSLog(@"array[0] = %@",array[0]);//array[0] =
   
    NSDictionary *dict = @{@"platform":@"ios",@"version":@"1.2"};

    NSLog(@"dict[0] = %@",dict[@"platform"]);//dict[0] = ios

 

 

8.UITextView如何关闭键盘

UITextField能够响应键盘上的完成按钮,关闭键盘,而UITextView不同,它的return按钮或者Done按钮执行的是换行功能,不能达到关闭键盘的目的。解决方法有两个:一个是经过捕捉touchEnd事件,当用户点击空白区域时关闭UITextView打开的键盘;一个是增长一个带有完成按钮的UIToolbar(这个UIToolbar当键盘弹出的时候老是显示在键盘的上方,很完美的贴在一块儿,键盘收起,它也会随着收起)。固然,将这两个方法都集成进来运用也是能够的。

   
下面提供第二种方法的详细代码:
    UIToolbar * topView = [[UIToolbar alloc]
initWithFrame:CGRectMake(0, 0, 320, 30)]; 
    [topView
setBarStyle:UIBarStyleDefault];
   
    UIBarButtonItem * btnSpace =
[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self
action:nil];
    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]
initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self
action:@selector(dismissKeyBoard)];   
    NSArray * buttonsArray = [NSArray
arrayWithObjects:btnSpace, doneButton, nil];

    [btnSpace release];

[doneButton release];

    [topView setItems:buttonsArray];
   
[m_myUITextView setInputAccessoryView:topView];
   
注:1.dismissKeyBoard是自定义的收起键盘的方法,可自定义其中的内容,好比执行[m_myUITextView

resignFirstResponder];

   2.最后一行代码setInputAccessoryView函数的调用是很关键的一句。

 

9.改变系统导航栏颜色字体


    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.titleTextAttributes = @{UITextAttributeTextColor: [UIColor whiteColor],
                                                                    UITextAttributeFont : [UIFont boldSystemFontOfSize:18]};

 

10.改变索引条背景和字体颜色

    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];

    self.tableView.sectionIndexColor = GRAY_BLUE_COLOR;

 

11.获取tableview最顶部和最底部的cell

// self.meAnswerTableView.visibleCells 当前可见的cell数组,该数组中得第一个cell就是顶部的headerCell,该数组中得最后一个cell就是顶部的footerCell
    NSLog(@"%d",self.meAnswerTableView.visibleCells.count);
    LCMeAnswerTableViewCell *cell = [self.meAnswerTableView.visibleCells objectAtIndex:0];
    // 获取顶部cell的index值
    if (cell != nil) {
        NSIndexPath *heaerIndex = [self.meAnswerTableView indexPathForCell:cell];
        NSLog(@"heaerindex.row = %d,heaerindex.section = %d",heaerIndex.row,heaerIndex.section);
    }
   
    LCMeAnswerTableViewCell *lastcell = [self.meAnswerTableView.visibleCells objectAtIndex:self.meAnswerTableView.visibleCells.count-1];
    if (lastcell != nil) {
        NSIndexPath *footerIndext = [self.meAnswerTableView indexPathForCell:lastcell];
        NSLog(@"footerIndext.row = %d,footerIndext.section = %d",footerIndext.row,footerIndext.section);

    }

12.设置tableview分割线


首先在viewDidLoad方法中加上以下代码:

    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {

[self.tableView setSeparatorInset:UIEdgeInsetsZero];

}

if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {

[self.tableView setLayoutMargins:UIEdgeInsetsZero];

}

而后在willDisplayCell方法中加入以下代码:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

{

if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {

[cell setSeparatorInset:UIEdgeInsetsZero];

}

if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {

[cell setLayoutMargins:UIEdgeInsetsZero];

}
 

}

xib设置以下

 

 

13.图片缓存

// 清理图片缓存 在viewdidload  或者 appdelegate 或者本身须要的地方调用
    [[SDImageCache sharedImageCache] clearDisk];
    [[SDImageCache sharedImageCache] clearMemory];
在tableview的- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法中调用
 // 从磁盘缓存中获取缓存图片,若是图片存在则直接调用,若是没有则下载。SDWebImageProgressiveDownload下载优先
                UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:avatar];
                if (image) {
                    photo.image = image;
                } else {
                    [photo setImageWithURL:[NSURL URLWithString:avatar] placeholderImage:[UIImage imageNamed:@"noavatar_big"]options:SDWebImageProgressiveDownload];

                }

14.建立单例(线程安全)

// 建立单例(线程安全)
+ (id) sharedTestModelSafe
{
    static XHTestModel *testModelSafe = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        testModelSafe = [[self alloc] init];
    });
    return testModelSafe;
}
// 建立单例
+ (id) sharedTestModel
{
    static XHTestModel *testModelShared = nil;
    if (testModelShared == nil) {
        testModelShared = [[XHTestModel alloc] init];
    }
    return testModelShared;

}

15.自适应Label高度

- (CGSize)getTextSize:(NSString *)text andFontSize:(CGFloat)fontSize andMaxSize:(CGSize)maxSize
{
    // 设置文章段落风格
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
   
    // 设置行间距
//    paragraphStyle.lineSpacing = 3.0f;
    // 设置段间距
//    paragraphStyle.paragraphSpacing = 20.0f;
   
    // 设置字体等属性:NSKernAttributeName(设置字间距)-该属性所对应的值是一个 NSNumber 对象(整数)。字母紧排指定了用于调整字距的像素点数。字母紧排的效果依赖于字体。值为 0 表示不使用字母紧排。默认值为0
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSParagraphStyleAttributeName:paragraphStyle,NSKernAttributeName:[NSNumber numberWithInt:4]};
    CGSize size = [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
   
    paragraphStyle.lineBreakMode=NSLineBreakByWordWrapping;
    // ceil返回大于或者等于指定表达式的最小整数
    size.height = ceil(size.height);
    size.width = ceil(size.width);
    return size;
    /*
    
注意若是这里设置了字间距,行间距和段间距,那么相应的label等控件也须要进行设置:
     UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, kScreenWidth-20, height)];
     label.text = text;
     label.numberOfLines = 0;
     label.font = [UIFont systemFontOfSize:14];
     label.textAlignment = NSTextAlignmentLeft;
    
     NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
     paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
     //
行间距
     paragraphStyle.lineSpacing = 3.0f;
     //
段间距
     paragraphStyle.paragraphSpacing = 20.0f;
    
     //
设置字体等属性
     NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14],NSParagraphStyleAttributeName:paragraphStyle};
     NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
     //
设置字间距
    
     long number = 0;
     // #import <CoreText/CoreText.h>
     CFNumberRef num = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt8Type, &number);
     [attr addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(0, [attr length])];
     CFRelease(num);
    
     #if 0
    
或者:
     NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14],NSParagraphStyleAttributeName:paragraphStyle,NSKernAttributeName:[NSNumber numberWithInt:4]};
     NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
   
     #endif
    
     label.attributedText = attr;
     */

}

16.键盘隐藏/显示+动态计算键盘高度+block通知

1. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealKeyboadShow:) name:UIKeyboardWillShowNotification object:nil];
    //键盘隐藏的事件通知

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealKeyboadHide:) name:UIKeyboardWillHideNotification object:nil];

 

//键盘显示事件通知的处理方法
-(void)dealKeyboadShow:(NSNotification *)noti
{
    NSLog(@"dealKeyboadShow");
   
    [UIView beginAnimations:@"" context:nil];
    [UIView setAnimationDuration:0.5];
   
    //处理键盘的遮挡
    loginButton.frame = CGRectMake(100, 210, 80, 30);
    registerButton.frame = CGRectMake(190, 210, 80, 30);
   
    [UIView commitAnimations];
}

-(void)dealKeyboadHide:(NSNotification *)noti
{
    NSLog(@"dealKeyboadShow");
   
    [UIView beginAnimations:@"" context:nil];
    [UIView setAnimationDuration:0.5];
   
    //处理键盘的遮挡
    loginButton.frame = CGRectMake(100, 400, 80, 30);
    registerButton.frame = CGRectMake(190, 400, 80, 30);
   
    [UIView commitAnimations];

}

 

 

 

2.block形式

 

// UIKeyboardWillShowNotification键盘即将显示Block形式

    [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        // 添加移动动画,使视图跟随键盘移动
        // 将通知中的信息转化成字典
        NSDictionary *infomation = [note userInfo];
        // 获取键盘展现结束以后的尺寸
        NSValue *value = [infomation objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGSize keyBoardSize = [value CGRectValue].size;
        // 键盘动画曲线
        NSNumber *curve = [infomation objectForKey:UIKeyboardAnimationCurveUserInfoKey];
        // 键盘的动画时间
        NSNumber *duration = [infomation objectForKey:UIKeyboardAnimationDurationUserInfoKey];
       
        [UIView animateWithDuration:[duration doubleValue] animations:^{
            [UIView setAnimationBeginsFromCurrentState:YES];
            [UIView setAnimationCurve:[curve intValue]];
            //处理键盘的遮挡
            loginButton.frame = CGRectMake(100, 500-keyBoardSize.height, 80, 30);
            registerButton.frame = CGRectMake(190, 500-keyBoardSize.height, 80, 30);
        } completion:^(BOOL finished) {
           
        }];

    }];
   
    [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillHideNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        // 添加移动动画,使视图跟随键盘移动
        // 将通知中的信息转化成字典
        NSDictionary *infomation = [note userInfo];
        // 获取键盘展现结束以后的尺寸
        NSValue *value = [infomation objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGSize keyBoardSize = [value CGRectValue].size;
        // 键盘动画曲线
        NSNumber *curve = [infomation objectForKey:UIKeyboardAnimationCurveUserInfoKey];
        // 键盘的动画时间
        NSNumber *duration = [infomation objectForKey:UIKeyboardAnimationDurationUserInfoKey];
       
        [UIView animateWithDuration:[duration doubleValue] animations:^{
            [UIView setAnimationBeginsFromCurrentState:YES];
            [UIView setAnimationCurve:[curve intValue]];
            //处理键盘的遮挡
            loginButton.frame = CGRectMake(100, 500, 80, 30);
            registerButton.frame = CGRectMake(190, 500, 80, 30);
        } completion:^(BOOL finished) {
           
        }];

 

    }];

 

3.block通知

// 通知  当获得消息的时候 把页面返回  返回的页面完成后才能够支持跳转
    [[NSNotificationCenter defaultCenter] addObserverForName:@"DismissDuihuaViewController" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        [self dismissViewControllerAnimated:YES completion:^{
            //            [self performSelector:@selector(presentDuihuaView) withObject:nil afterDelay:0.5];
            //            [[NSNotificationCenter defaultCenter] postNotificationName:@"presentDuihuaView" object:nil];
        }];
        [self.navigationController popViewControllerAnimated:YES];
        [self performSelector:@selector(presentDuihuaView) withObject:nil afterDelay:0.5];

    }];

相关文章
相关标签/搜索