iOS開発の一般的な知識点のまとめ

11329 ワード

ここにiOS開発でよく使われているメモを記録して、次回の使用に便利です.
-------ナビゲーター関連-------
  • グローバル設定ナビゲーションバー戻るボタン
  • //             
    [[UIBarButtonItem appearance] setTintColor:[UIColor blackColor]]; 
    //                      
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
    //     iOS11    ,  iOS11                 。       ,             
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal];
    
  • ナビゲーションバータイトル
  • を設定する.
    //self.title = @"  ";         tabbarController        
    self.navigationItem.title = @"  ";
    
  • 右スライドpop機能
  • //    pop     YES。
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    //      leftBarButtonItem         ,                   pop
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    

    ---------- UITableView ----------
  • UITableViewStyle
  • UITableViewStylePlain,          // regular table view     
    UITableViewStyleGrouped         // preferences style table view       
    

    違い:UItableViewStylePlain:1.複数のsectionがある場合、ヘッダは上部に留まり、tableViewとともにスライドすることはない.頭と真ん中の間隔はありません.UITableViewStyleGrouped: 1.ヘッダーは上部にとどまらず、tableViewとともにスライドする.デフォルトでは、頭部の尾部距離と領域間隔が設定されています.(間隔を外してtableView.tableHeaderViewまたはtableView.tableFooterViewまたは実装エージェントメソッドを設定できます.注意設定の高さはゼロではなく、ゼロであればアップルはデフォルト値をとることでヘッダ間隔を解消できません)
  • 分割線
  • //     
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //     
    tableView.separatorColor = [UIColor redColor];
    //tableView       (top, left, bottom, right)
    tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    //cell          
    cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
  • UITableViewCellStyle
  • UITableViewCellStyleDefault,    // Simple cell with text label and optional image view (behavior of UITableViewCell in iPhoneOS 2.x)
    UITableViewCellStyleValue1,     // Left aligned label on left and right aligned label on right with blue text (Used in Settings)
    UITableViewCellStyleValue2,     // Right aligned label on left with blue text and left aligned label on right (Used in Phone/Contacts)
    UITableViewCellStyleSubtitle    // Left aligned label on top and left aligned label on bottom with gray text (Used in iPod).
    

    違い:Default:デフォルトスタイル、メインタイトルのみ、サブタイトルValue 1:左メインタイトルtextLabel、右サイドサブタイトルdetailTextLabel、メインタイトルフォント比較黒Value 2:左メインタイトルtextLabelフォントが小さく、メインタイトル右側にサブタイトルdetailTextLabelが隣接し、フォントが大きく黒Subtitle:メインタイトルtextLabelが上にあり、フォントが大きく黒になります.サブタイトルdetailTextLabelはメインタイトルの下にフォントが小さい
  • UITableViewCellSelectionStyle

  • 個人的にはNone以外の3つは同じ効果だと思いますが、いずれもグレーです
    //UITableViewCellSelectionStyleNone
    //UITableViewCellSelectionStyleBlue
    //UITableViewCellSelectionStyleGray
    //UITableViewCellSelectionStyleDefault
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    

    選択したcellバックグラウンドをカスタマイズします.選択したバックグラウンドをカスタマイズするにはcellのselectionsStyleプロパティをUITableViewCellSelectionsStyleNoneに設定できません.
    //     cell     
    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
    cell.selectedBackgroundView.backgroundColor = [UIColor redColor];
    //     cell     
    cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"picture"]];
    
  • UITableViewCellAccessoryType
  • //UITableViewCellAccessoryNone
    //UITableViewCellAccessoryDisclosureIndicator                   
    //UITableViewCellAccessoryDetailDisclosureButton                 
    //UITableViewCellAccessoryCheckmark                             
    //UITableViewCellAccessoryDetailButton                           
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
  • ゾーンまたはロー
  • をリフレッシュ
    //  section      
    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1]; //           
    [tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];  
    //  cell      
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0];  //          cell  
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    

    ---------- cocoapods ----------
    pod install--verbose--no-repo-updateこのコマンドは新しく追加したライブラリのみをインストールし、更新されたライブラリは無視します.
    pod updateライブラリ名--verbose--no-repo-updateこのコマンドは指定したライブラリのみを更新し、他のライブラリは無視します.
    --------よく使われるマクロ定義--------
    //     
    #ifdef DEBUG
    #define DLog(format, ...) printf("class:  method: %s 
    %s
    ", self, [[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, __PRETTY_FUNCTION__, [[NSString stringWithFormat:(format), ##__VA_ARGS__] UTF8String] ) #else #define DLog(format, ...) #endif // #define kScreenWidth [UIScreen mainScreen].bounds.size.width #define kScreenHeight [UIScreen mainScreen].bounds.size.height #define kPercenX_scale(value) (value *WIDTH/375)// iPhone 8 —— #define kPercenY_scale(value) (value *HEIGHT/667)// iPhone 8 —— #define kTopHeight_SafeArea (SCRE_HEIGHT == 812.0 ? 88 : 64)// iPhone X 88 #define kBottomHeight_SafeArea (SCRE_HEIGHT == 812.0 ? 34 : 0)// iPhone X 34 // #define UIColorFromRGB(r, g, b) [UIColor colorWithRed:(r)/255.0 \ green:(g)/255.0 blue:(b)/255.0 alpha:1.0]//RGB #define UIColorFromRGBA(r, g, b, a) [UIColor colorWithRed:(r)/255.0 \ green:(g)/255.0 blue:(b)/255.0 alpha:a]//RGBA #define UIColorFromHEX(rgbValue) [UIColor \ colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \ green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \ blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]// RGB #define UIColorFromHEXA(rgbValue, alphaValue) [UIColor \ colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \ green:((float)((rgbValue & 0x00FF00) >> 8))/255.0 \ blue:((float)(rgbValue & 0x0000FF))/255.0 alpha:alphaValue]// RGBA #define UIColorFromRandom [UIColor colorWithRed:(arc4random_uniform(256))/255.0 \ green:(arc4random_uniform(256))/255.0 \ blue:(arc4random_uniform(256))/255.0 alpha:1.0]// // #define weakSelf __weak __typeof(&*self)weakSelf = self;

    -------電話でメールを送る-------
  • 電話
  • //1. openURL                
    //NSString *str = @"telprompt://10010";  API,             
    NSString *str = @"tel:10010";
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str] options:@{} completionHandler:nil];
    //2. UIWebView                (    )
    NSString *str = @"tel:10010";
    UIWebView *callWebView = [[UIWebView alloc] init];
    NSURL *telURL = [NSURL URLWithString:str];
    [callWebView loadRequest:[NSURLRequest requestWithURL:telURL]];
    [self.view addSubview:callWebView];
    
  • メール
  • //1.           ,              
    NSString *str = @"sms://10010";
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str] options:@{} completionHandler:nil];
    //2.  MessageUI       ,           ,            
    #import 
    MFMessageComposeViewController *vc = [[MFMessageComposeViewController alloc]init];
    vc.body = @"    ";//      
    vc.recipients = @[@"10010",@"10086"];//       
    vc.messageComposeDelegate = self;//    
    [self presentViewController:vc animated:YES completion:nil];
    #pragma mark - MFMessageComposeViewControllerDelegate
    - (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
    {
        [controller dismissViewControllerAnimated:YES completion:nil];
    }
    

    --------valueForKeyPathの使用--------
    注:この段落の内容は転載しますhttp://www.cocoachina.com/ios/20180629/23983.html
  • 配列の最大値、最小値、平均値、および合計値
  • を取得する.
    CGFloat max = [[array valueForKeyPath:@"@max.floatValue"] floatValue];
    CGFloat min = [[array valueForKeyPath:@"@min.floatValue"] floatValue];
    CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
    CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
    
  • 配列中の同じkeyの要素
  • を取得する
    NSArray *arr = @[@{@"city":@"beijing",@"person":@{@"name":@"zhangsan"}},@{@"city":@"chengdu"}];
    [arr valueForKeyPath:@"city"];
    //     city   @[@"beijing",@"chengdu"]
    //
    
  • が使用可能である.下へのインデックス
  • NSDictionary *dict1 = @{@"dic1":@{@"dic2":@{@"name":@"lisi",@"info":@{@"age":@"12"}}}};
    id res = [dict1 valueForKeyPath:@"[dict1.dict2.name];
    
  • 重複するデータを削除する
  • .
    NSArray *array = @[@"qq", @"wechat", @"qq", @"msn", @"wechat"];
    [array valueForKeyPath:@"@distinctUnionOfObjects.self"];
    
  • ネスト使用(対応する値の重複データを削除してから値を取る)
  • NSArray *array = @[@{@"name" : @"xiaoming",
                      @"code" : @1},
                     @{@"name": @"judy",
                      @"code" : @2},
                     @{@"name": @"judy",
                      @"code" : @3},
                     @{@"name": @"xiaohua",
                      @"code" : @4}];
    [array valueForKeyPath:@"@distinctUnionOfObjects.name"];
    
  • UItextfieldのplaceholderの色を変える
  • [addressTextField  setValue:[UIColor redColor] forKeyPath:@”_placeholderLabel.textColor”];
    //     - (void)drawPlaceholderInRect:(CGRect)rect;      !
    

    --------その他の冷たい知識--------
  • 一部のシステムのものは英語で表示され、plistの中の:Localization native development regionのenをZnに変更すれば
  • である.
  • ステータスバーの色を変更
  • [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
  • UIalertControllerフォント色を変更
  • //         
    alertController.view.tintColor = [UIColor blackColor];
    //         
    [cancleAction setValue:[UIColor grayColor] forKey:@"_titleTextColor"];
    
  • label動的取得高さ、textはlabelの文字、widthはlabelの幅
  • CGFloat labelHeight = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size.height;
    
  • label属性文字列変更色
  • NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:title];
        [attributedStr addAttribute:NSForegroundColorAttributeName value:COLOR range:NSMakeRange(0, 4)];
    
  • 現在のviewに従って所在するcontroller
  • を取得する
    - (UIViewController *)viewControllerSupportView:(UIView *)view {
        for (UIView* next = [view superview]; next; next = next.superview) {
            UIResponder *nextResponder = [next nextResponder];
            if ([nextResponder isKindOfClass:[UIViewController class]]) {
                return (UIViewController *)nextResponder;
            }
        }
        return nil;
    }
    
  • 現在のviewControllerの参照カウント
  • を取得する
    NSLog(@"Retain count is %ld", CFGetRetainCount((__bridge CFTypeRef)self));
    

    未完待続...