iOS小記錄

Table&TableCell相關

加載XIB 自定義 TableViewCell(cell需要有不同的cellID)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyCustomCell * cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
    if (!cell) {
        [tableView registerNib:[UINib nibWithNibName:@"MyCustomCell" bundle:nil] forCellReuseIdentifier:@"myCell"];
        cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
    }
    return cell;
}
獲取當前cell在當前屏幕中的frame
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];
    CGRect rect = [tableView convertRect:rectInTableView toView:tableView.superview];
}


提交審核,隱私網址

  • xcode工程中,集成了ping++ 支付SDK,ping++開發文檔中說明需要在Capabilities中開啟 Apple Pay。
  • 提交審核時,提示:
    使用權限 [com.apple.developer.in-app-payments] 的 App 必須為[Simplified Chinese]提供隱私政策網址(URL)。如果您的 App ?不使用這些權限,請將它們從您的 App 中移除并上傳新的二進制文件。
  • 上網Google后得知,是因為開啟了Apple Pay功能,而未提供隱私政策網址導致。

解決方法1
不再使用Apple Pay(停用Apple Pay權限)

  1. 在 Capabilities 里關掉不使用的權限(此處為 Apple Pay),再看一下項目文件中是否有用到改權限配置文件或者配置信息,全部清理掉。
  2. 登錄https://developer.apple.com/ ,在App IDs中關掉這些不使用的權限
  3. 重新下載證書和重新打包,再上傳 App Store 提交時就會看到提交成功,不再報錯。

解決方法2
提供隱私政策網址

  1. 進入 iTunes Connect -> 我的APP -> App信息
  2. 添加隱私政策網址(URL)
    此網址
  • 可以是你app注冊的協議的網址
  • 或者可以網上搜一下 隱私政策 ,提交到新浪博客等處(一個網址)
  • 然后把該網址填上去保存


動畫相關

常用animationKeyPath總結
Paste_Image.png

修改xib約束使之有動畫效果

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topMargin;

[UIView animateWithDuration:0.25f animations:^{
        self.topMargin.constant += 50;
        // 預使修改約束有動畫效果,需要調用一下方法
        // subView 約束的對象
        [self.subView layoutIfNeeded];
    } completion:^(BOOL finished) {
    }];


鍵盤相關

關閉鍵盤聯想功能
self.textView.autocorrectionType = UITextAutocorrectionTypeNo;
self.textField.autocorrectionType = UITextAutocorrectionTypeNo;
Return鍵在輸入框無內容時置灰
// 這里設置Return鍵為無文字就灰色不可點
self.textField.enablesReturnKeyAutomatically = YES; 
解決 切換明文/密文顯示末尾空白的 bug
- (void)secureSwitchAction:(id)sender {
    self.passwordTextField.secureTextEntry = !self.passwordTextField.secureTextEntry;

    NSString *text = self.passwordTextField.text;
    self.passwordTextField.text = @" ";
    self.passwordTextField.text = text;
}
中文輸入法問題

iOS系統鍵盤在輸入中文到textField、textView,英文會進入到文本框里響應代理方法的問題

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textFieldDidChange:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:self.inputTF];

- (void)textFieldDidChange:(NSNotification *)noti {
    UITextField *textField = (UITextField *)noti.object;
    NSString *textString = textField.text;
    // 鍵盤輸入模式
    NSString *lang = textField.textInputMode.primaryLanguage;
    // 簡體中文輸入,包括簡體拼音,健體五筆,簡體手寫
    if ([lang isEqualToString:@"zh-Hans"]) {
        UITextRange *selectedRange = [textField markedTextRange];
        // 獲取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 沒有高亮選擇的字,則對已輸入的文字進行處理
        if (!position) {
            // 去除字符串兩邊的空格
            textField.text = [textString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            // TODO: 其他自定義操作
        } else {
            // 有高亮選擇的字符串,則暫不對文字進行處理
        }
    } else {
        // 中文輸入法以外的輸入法
        // 去除字符串兩邊的空格
        textField.text = [textString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        // TODO: 其他自定義操作
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


時間相關

設置UIDatePicker的允許最大時間、最小時間
// UIDatePicker初始化
self.frame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height);
datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, CGRectGetWidth(self.frame), 216)];
datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh-Hans"]; // 設置默認的地區
datePicker.backgroundColor = [UIColor whiteColor];

// 設置最小、最大時間
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:10];//設置最大時間為:當前時間推后十年
NSDate *maxDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
[comps setYear:-10];//設置最小時間為:當前時間前推十年
NSDate *minDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];

[datePicker setMaximumDate:maxDate];
[datePicker setMinimumDate:minDate];


字符串(Label)相關

改變行間距、字間距
+ (void)changeLineSpaceForLabel:(UILabel *)label WithSpace:(float)space {
    NSString *labelText = label.text;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:space];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
    label.attributedText = attributedString;
    [label sizeToFit];
}

+ (void)changeWordSpaceForLabel:(UILabel *)label WithSpace:(float)space {
    NSString *labelText = label.text;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText attributes:@{NSKernAttributeName:@(space)}];
    label.attributedText = attributedString;
    [label sizeToFit];
}

+ (void)changeSpaceForLabel:(UILabel *)label withLineSpace:(float)lineSpace WordSpace:(float)wordSpace {
    NSString *labelText = label.text;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText attributes:@{NSKernAttributeName:@(wordSpace)}];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpace];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
    label.attributedText = attributedString;
    [label sizeToFit];
}

封裝AFN - POST

/// 封裝POST請求
+ (void)post:(NSString *)urlStr
       param:(id)param
     success:(void (^)(NSDictionary *resultDict))success
     failure:(void (^)(NSError *error))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 拒絕自動解析
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 使用cookie
    manager.requestSerializer.HTTPShouldHandleCookies = YES;
    // 設置請求頭
    [manager.requestSerializer setValue:@"XMLHttpRequest" forHTTPHeaderField:@"X-Requested-With"];
    [manager.requestSerializer setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"];

    // 設置超時時間
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = TimeoutInterval;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    /// 讀取和設置Cookie
    __block NSUserDefaults *uds = [NSUserDefaults standardUserDefaults];
    NSData *cookiesdata = [uds objectForKey:kUserDefaultsCookie];
    NSLog(@"請求前");
    if(cookiesdata.length) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSMutableDictionary *mutParam = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)param];
    NSDictionary *urlExt = [uds valueForKey:TokenKV];
    [mutParam setValuesForKeysWithDictionary:urlExt];
    NSLog(@"\npostUrl   : %@\nparameter : %@", urlStr, mutParam);
    
    [manager POST:urlStr
       parameters:mutParam
         progress:nil
          success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
              /// 保存Cookies
              NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
              if (cookies) {
                  NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cookies];
                  [uds setObject:data forKey:kUserDefaultsCookie];
                  [uds synchronize];
              }
              
              NSError *error = nil;
              /// 解析數字,如果數字在 [10e-128, 10e127] 范圍外,解析失敗,因為NSNumber放不下區間外的數字,導致解析為 NaN
              NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
              if (success) {
                  success(dict);
              }
              
          }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              if (error.code == -1009) {
                  [ZXCusAlert alertWithTitles:@[@"網絡連接錯誤"]];
              }
              if (failure) {
                  failure(error);
              }
          }];
}

這只請求頭

    // 設置請求頭
    [manager.requestSerializer setValue:@"XMLHttpRequest" forHTTPHeaderField:@"X-Requested-With"];
    // 設置解析語言
    [manager.requestSerializer setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"];
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容