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];

    }];

相關文章
相關標籤/搜索