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中关掉这些不使用的权限
    iOS小记录_第1张图片
  3. 重新下载证书和重新打包,再上传 App Store 提交时就会看到提交成功,不再报错。

解决方法2
提供隐私政策网址

  1. 进入 iTunes Connect -> 我的APP -> App信息
    iOS小记录_第2张图片
  2. 添加隐私政策网址(URL)
    此网址
  • 可以是你app注册的协议的网址
  • 或者可以网上搜一下 隐私政策 ,提交到新浪博客等处(一个网址)
  • 然后把该网址填上去保存


动画相关

常用animationKeyPath总结
iOS小记录_第3张图片
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"];

你可能感兴趣的:(iOS小记录)