OC Code Block Backups

OC Code Block Backups_第1张图片

简单粗暴 不定期更新(始于161011)......

  1. btn对齐
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
  1. 子控件可以继承父控件的alpha,如果只需要设置父视图的alpha可以使用rgb
self.chooseBrandVC = [WMChooseBrandVC new];
self.chooseBrandVC.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
self.chooseBrandVC.view.frame = CGRectMake(0, 0, _width_, _height_);
[self.view addSubview:self.chooseBrandVC.view];
[self addChildViewController:self.chooseBrandVC];
OC Code Block Backups_第2张图片
  1. btn 文字分行
[_sellingClothingBtn setTitle:@"  正经营\n 服装生意" forState:UIControlStateNormal];
_sellingClothingBtn.titleLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
_sellingClothingBtn.titleLabel.numberOfLines = 2;
  1. 判断一个触摸点是否在一个区域内
// CGGeometry.h
// CG_EXTERN bool CGRectContainsPoint(CGRect rect, CGPoint point)
// CG_EXTERN bool CGRectContainsRect(CGRect rect1, CGRect rect2)
 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];
        CGPoint point = [touch locationInView:self.view];
        if (!CGRectContainsPoint(self.tableView.frame, point)) {
            self.didChooseBrandBlock();
        }
}
  1. 延迟执行
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3  * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
     // do sth.
});
  1. IBOutletCollection 今天碰到了这个,先记录,等有时间在详细记录下
@property (nonatomic, strong) IBOutletCollection(UILabel) NSArray *titleLabel;
  1. 监听textField的文字改变
// 不使用 UIControlEventValueChanged
// 使用 UIControlEventEditingChanged
[_textField addTarget:self action:@selector(textFieldTextDidChange:) forControlEvents:UIControlEventEditingChanged];
  1. 隐藏导航栏
// 动画YES 会流畅一些
// 方法1 
 - (void)viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
        [self.navigationController setNavigationBarHidden:NO animated:YES];
}
 - (void)viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
        [self.navigationController setNavigationBarHidden:NO animated:YES];
}
// 方法2
self.navigationController.delegate = self;
 - (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
        [self.navigationController setNavigationBarHidden:[viewController isKindOfClass:self.class] animated:YES];
}
  1. 设置rightBarButtonItem的字体
UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(didClickBarButton:)];
self.navigationItem.rightBarButtonItem = rightBarButton;
[self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13], NSForegroundColorAttributeName : FFColorFromRGB_0x(0x666666)} forState:UIControlStateNormal];
OC Code Block Backups_第3张图片
  1. xib中使用十六进制来设置控件颜色
    如图:
OC Code Block Backups_第4张图片
  1. 属性字体嵌套
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"\t您上周的合伙人"];
NSAttributedString *appendStr = [[NSAttributedString alloc] initWithString:@" 1 " attributes:@{NSForegroundColorAttributeName : FFColorFromRGB_0x(0xb53a34)}];
[str appendAttributedString:appendStr];
appendStr = [[NSAttributedString alloc] initWithString:@"人,还差"];
[str appendAttributedString:appendStr];
appendStr = [[NSAttributedString alloc] initWithString:@" 7 " attributes:@{NSForegroundColorAttributeName : FFColorFromRGB_0x(0xb53a34)}];
[str appendAttributedString:appendStr];
appendStr = [[NSAttributedString alloc] initWithString:@"个才能升级为盟主,本周合伙人数量:"];
[str appendAttributedString:appendStr];
appendStr = [[NSAttributedString alloc] initWithString:@"2 " attributes:@{NSForegroundColorAttributeName : FFColorFromRGB_0x(0xb53a34)}];
[str appendAttributedString:appendStr];
appendStr = [[NSAttributedString alloc] initWithString:@"人,还差"];
[str appendAttributedString:appendStr];
appendStr = [[NSAttributedString alloc] initWithString:@" 5 " attributes:@{NSForegroundColorAttributeName : FFColorFromRGB_0x(0xb53a34)}];
[str appendAttributedString:appendStr];
appendStr = [[NSAttributedString alloc] initWithString:@"个才能升级为盟主,您当前的佣金总数:"];
[str appendAttributedString:appendStr];
appendStr = [[NSAttributedString alloc] initWithString:@"¥888 " attributes:@{NSForegroundColorAttributeName : FFColorFromRGB_0x(0xb53a34)}];
[str appendAttributedString:appendStr];
appendStr = [[NSAttributedString alloc] initWithString:@"(加油哦,您还不能够升级为盟主)。"];
[str appendAttributedString:appendStr];
self.explainLabel.attributedText = str;
OC Code Block Backups_第5张图片
  1. colloectionView 相关
 - (UICollectionView *)collectionView {
      if (!_collectionView) {
          CGFloat itemWidth = (SCREEN_WIDTH - 30.0) / 2.0;
          CGFloat itemHeight = 30;
          UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
          flowLayout.itemSize = CGSizeMake(itemWidth, itemHeight);
          flowLayout.minimumLineSpacing = 5;
          flowLayout.minimumInteritemSpacing = 5;
          flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10); // 距离上下左右
          _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
          _collectionView.delegate = self;
          _collectionView.dataSource = self;
          _collectionView.showsVerticalScrollIndicator = NO;
          _collectionView.backgroundColor = [UIColor clearColor];
          [_collectionView registerNib:[UINib nibWithNibName:@"GoodsCategoryCell" bundle:nil] forCellWithReuseIdentifier:@"cellItem"];
          [_collectionView registerNib:[UINib nibWithNibName:@"GoodsCategoryHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
      }
      return _collectionView;
 }
  1. xib中的自适应 (和代码相结合)
// 首先按照最小值设置约束,然后在调整约束为 >= ,记着把label的numberofrows更改
// 在设置label的高度自适应,在heightforrow中 根据文字的宽度或者高度 适配高度
OC Code Block Backups_第6张图片

.


OC Code Block Backups_第7张图片

.


OC Code Block Backups_第8张图片
  1. label的文字的行间距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentCenter;
    paragraphStyle.lineSpacing = 10; // 行间距
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:@"天青色等烟雨 天青色等烟雨 天青色等烟雨 \n 而我在等你" attributes:@{NSParagraphStyleAttributeName : paragraphStyle}];
    label.attributedText = attString;
OC Code Block Backups_第9张图片
  1. 调用相机或相册
 - (void)choosePhotoButtonClick {   
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"title" message:@"message" preferredStyle:UIAlertControllerStyleActionSheet];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"\n-----> 取消");
        }]];
        WeakSelf(self);
        [alertController addAction:[UIAlertAction actionWithTitle:@"打开相机呐" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"\n-----> 打开相机呐");
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                [weakSelf getPhotoWithSourceType:UIImagePickerControllerSourceTypeCamera];
            } else {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"标题" message:@"您的设备无法拍照,请检查设备" preferredStyle:UIAlertControllerStyleAlert];
                [alertController addAction:[UIAlertAction actionWithTitle:@"知道啦" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                      NSLog(@"\n-----> 取消了");
                 }]];
                 [weakSelf presentViewController:alertController animated:YES completion:nil];
            }
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"打开相册呐" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"\n-----> 打开相册呐");
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                [weakSelf getPhotoWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            } else {
                [weakSelf getPhotoWithSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
            }
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
}
// 修改头像调用系统相机和系统相册
 - (void)getPhotoWithSourceType:(UIImagePickerControllerSourceType)sourceType {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.sourceType = sourceType;
        imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = NO;
        [self presentViewController:imagePickerController animated:YES completion:nil];
}
// UIImagePickerControllerDelegate
 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
        NSLog(@"\n-----> %@", info);
        NSString *imgUrl = info[UIImagePickerControllerReferenceURL];
        ALAssetsLibrary* assetslibrary = [ALAssetsLibrary new];
        [assetslibrary assetForURL:pathStr resultBlock:^(ALAsset *asset) {
            CGImageRef  ref = [asset thumbnail]; // 缩略图
            // CGImageRef ref = [[asset  defaultRepresentation] fullScreenImage]; 全屏
            // CGImageRef ref = [[asset  defaultRepresentation] fullResolutionImage]; 高清
            imgView.image = [[UIImage alloc] initWithCGImage:ref];
        } failureBlock:^(NSError *error) {
            // 请重新选择图片
        }];
         [picker dismissViewControllerAnimated:YES completion:^{
             [UIApplication sharedApplication].statusBarHidden = NO;
             [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
             UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
             self.imgView.image = image;
         }];
}
 - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
        [picker dismissViewControllerAnimated:YES completion:^{
            [UIApplication sharedApplication].statusBarHidden = NO;
            [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        }];
}
  1. 保存图片到相册
// Adds a photo to the saved photos album.  The optional completionSelector should have the form:
//  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
UIKIT_EXTERN void UIImageWriteToSavedPhotosAlbum(UIImage *image, __nullable id completionTarget, __nullable SEL completionSelector, void * __nullable contextInfo) __TVOS_PROHIBITED;
// 参数1:所保存的图片    参数2:保存完成后回调方法所在的对象    参数3:保存完成后的回调   参数4:可选的参数,保存了一个指向context数据的指针,将传递给回调方法
 - (void)saveImgClick {
        UIImage *img = [UIImage imageNamed:@"default"];
        UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
 }
 - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
        NSString *message = @"";
        if(error == NULL) {
            message = @"图片保存相册失败";
        } else {
            message = @"图片保存相册成功";
        }
 }
  1. 复制
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = textfield.text;
NSString *str = pasteboard.string;
  1. 当使用tableview自带的分割线的时候会在没有cell的时候出现多余的线 如下设置
self.tableview.tableFooterView = [UIView new];
  1. 删除线
typedef NS_ENUM(NSInteger, NSUnderlineStyle) { // 下划线 或者 删除线 的样式
        NSUnderlineStyleNone                                    = 0x00, 
        NSUnderlineStyleSingle                                  = 0x01, // 细单
        NSUnderlineStyleThick NS_ENUM_AVAILABLE(10_0, 7_0)      = 0x02, // 粗单
        NSUnderlineStyleDouble NS_ENUM_AVAILABLE(10_0, 7_0)     = 0x09, // 细双

        NSUnderlinePatternSolid NS_ENUM_AVAILABLE(10_0, 7_0)      = 0x0000, // 实线
        NSUnderlinePatternDot NS_ENUM_AVAILABLE(10_0, 7_0)        = 0x0100, // 样式为点(虚线)---
        NSUnderlinePatternDash NS_ENUM_AVAILABLE(10_0, 7_0)       = 0x0200, // 样式为破折号 —— —— ——
        NSUnderlinePatternDashDot NS_ENUM_AVAILABLE(10_0, 7_0)    = 0x0300, // 样式为连续的破折号和点 ——-——-——-
        NSUnderlinePatternDashDotDot NS_ENUM_AVAILABLE(10_0, 7_0) = 0x0400, // 样式为连续的破折号、点、点 ——--——--——--

        NSUnderlineByWord NS_ENUM_AVAILABLE(10_0, 7_0)            = 0x8000 // 有空格的地方不设置下划线
} NS_ENUM_AVAILABLE(10_0, 6_0);
[mAttrStr addAttributes:@{NSStrikethroughStyleAttributeName : @(NSUnderlineStyleSingle)} range:[mAttrStr.string rangeOfString:markPri]];
  1. tableHeaderView tableFooterView
不要和...混淆
// accessory view for above row content. default is nil. not to be confused with section header 
@property (nonatomic, strong, nullable) UIView *tableHeaderView; 
// accessory view below content. default is nil. not to be confused with section footer
@property (nonatomic, strong, nullable) UIView *tableFooterView;                           
  1. 偷巧修改cell内容
    图1 -> 图2,如图3设置 为负值
OC Code Block Backups_第10张图片
图1

OC Code Block Backups_第11张图片
图2

OC Code Block Backups_第12张图片
图3
  1. xib 和 vc 关联


    OC Code Block Backups_第13张图片

    OC Code Block Backups_第14张图片

    OC Code Block Backups_第15张图片
  2. shareSDK 授权微信登录
 - (void)loginWithWxClick {
        WeakSelf(self);
        if (![ShareSDK hasAuthorized:SSDKPlatformTypeWechat]) {//未授权
              //去授权
            [ShareSDK authorize:SSDKPlatformTypeWechat settings:nil onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
                if (state == SSDKResponseStateSuccess) {
                    NSLog(@"微信授权成功!");
                    // 使用微信信息登录
                    [weakSelf requestWXLoginWithSSDKUser:user];
                } else {
                    NSLog(@"微信授权失败! %@",error);
                }
            }];
          } else {
            [ShareSDK getUserInfo:SSDKPlatformTypeWechat onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
                if (state == SSDKResponseStateSuccess) {
                    NSLog(@"微信已经授权,获取用户信息");
                    [weakSelf requestWXLoginWithSSDKUser:user];
                } else {
                    NSLog(@"微信授权失败! %@",error);
                }
            }];
         }
 }
  1. cell xib 中 存在accessoryType 的布局
    cell 的 accessoryType 不一定存在,约束思路:可以在xib中 只约束左侧的label,右侧的label在 代码中约束 (如果在xib中约束了右侧label,然后在 layoutsubviews中重新对其布局 --- 无效)
  - (void)layoutSubviews {
        [super layoutSubviews];

        [self.contentLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.height.equalTo(self.titleLabel);
            make.left.equalTo(self.titleLabel.mas_right).offset(0);
            if (self.accessoryType == UITableViewCellAccessoryDisclosureIndicator) {
                make.right.mas_equalTo(0);
            } else {
                make.right.mas_equalTo(-13);
            }
        }];
}

其实 使用 UITableViewCellStyleValue1,即可 [捂脸][捂脸][捂脸]

OC Code Block Backups_第16张图片
  1. 跳转到评论
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=***"]];
  1. 监听键盘变化
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangeKeyboardFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];
 - (void)didChangeKeyboardFrameNotification:(NSNotification *)notification {
        CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        [UIView animateWithDuration:[[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
            self.view.frame = CGRectMake(0, -self.view.height+rect.origin.y, _width_, _height_);
        }];
 }
  1. 两个横向自适应的label 使用xib添加约束
OC Code Block Backups_第17张图片

可以固定 a 或 b,其中一边的距离即可,如果两边都添加约束的话 会出现如下图情况


OC Code Block Backups_第18张图片
  1. 监听textview 的键盘右下角点击
 textfield 有如下两个代理方法,但是 textview 没有
 - (BOOL)textFieldShouldClear:(UITextField *)textField;  // called when clear button pressed. return NO to ignore (no notifications)
 - (BOOL)textFieldShouldReturn:(UITextField *)textField;  // called when 'return' key pressed. return NO to ignore.
// self.textView.returnKeyType = UIReturnKeyDone;
 - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
      if ([text isEqualToString:@"\n"]) {  // 按下return
          // do sth.
          [textView resignFirstResponder];
          return NO; // 返回NO 代表return失效 (页面上按下return,不会出现换行,如果为yes,则输出页面会换行)
      }
      return YES;
 }
  1. setter、getter
 - (void)setTextNomalColor:(UIColor *)textNomalColor{
       if (_textNomalColor != textNomalColor) {
           for (UIButton *subButton in self.buttonsArray){
               [subButton setTitleColor:textNomalColor forState:UIControlStateNormal];
           }
           _textNomalColor = textNomalColor;
       }
 }
  1. button imgview 或 label 相对位置
[button setTitleEdgeInsets:UIEdgeInsetsMake(0, -6, 0, 0)];
[button setImageEdgeInsets:UIEdgeInsetsMake(0, 64, 0, 0)];
  1. 数组限制
NSArray *infoArray = ......;
  1. xib中设置tablecell 下划线左右距离
OC Code Block Backups_第19张图片
  1. button高亮闪烁状态
// 需要在 Custom 状态下才有效
button.adjustsImageWhenHighlighted = NO;
  1. collection reloadSections 时候 会出现闪烁动画
    [UIView performWithoutAnimation:^{
         [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:1]];
   }];
  1. 在storybord或xib中设置 button的圆角
    layer.masksToBounds
    layer.cornerRadius
OC Code Block Backups_第20张图片
  1. 测试的时候,怎么切换 手机 和 模拟器
OC Code Block Backups_第21张图片
  1. 更换状态栏颜色
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    statusBar.backgroundColor = [UIColor redColor];

 不定期更新 不合适的地方 还请指点~ 感激不尽

你可能感兴趣的:(OC Code Block Backups)