objectivec 代码初始化细胞

TableViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self initWithView];
    }
    return self;
}
// 在这个方法里面添加各种控件,但是不要在这个方法里面设置控件的尺寸大小
- (void)initWithView {
    
}
// 在这个方法里面设置尺寸大小
- (void)layoutSubviews {
    [super layoutSubviews];
}

objectivec UITableView加载单元的几种常用方式

tableCell
方法一:
// 1.注册Cell
1.[self.tableView registerClass:[TableViewCell class] forCellReuseIdentifier:ID];
2.[tableView registerNib:[UINib nibWithNibName:@"TableViewCell" bundle:nil] forCellReuseIdentifier:IDENTIFIER];
// 2.循环Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%s", __func__);
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    return cell;
}
// 方法二:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCellId"];
    if (!cell) {
        cell =  [[NSBundle mainBundle]loadNibNamed:@"TableViewCell" owner:self options:nil].firstObject;
    }
    return cell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCellId"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:0 reuseIdentifier:idfity];
    }
    return cell;
}

objectivec UITableViewCell中去掉点击效果

UITableViewCell
// 方法一
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//当手指离开某行时,就让某行的选中状态消失
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

// 方法二
//UITableViewCell *cell;
cell.selectionStyle = UITableViewCellSelectionStyleNone;

objectivec 获取Autolayout某个控件的尺寸

autolayout

CGSize size = [self.cellImageView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];

objectivec 图片圆角的三种方式

cornerRadius
方式一:通过 layer 设置圆角
 // 创建图片框
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    // 添加图片
    imageView.image = [UIImage imageNamed:@"104.jpg"];
    // 使用 layer 设置圆角
    imageView.layer.cornerRadius = 50;
    imageView.layer.masksToBounds = YES;
    [self.view addSubview:imageView];

方式二:使用贝塞尔曲线UIBezierPath和Core Graphics框架画出一个圆角

// 创建图片框
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    // 添加图片
    imageView.image = [UIImage imageNamed:@"104.jpg"];
    //开始对imageView进行画图
    UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
    //使用贝塞尔曲线画出一个圆形图
    [[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:imageView.frame.size.width] addClip];
    [imageView drawRect:imageView.bounds];

    imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    //结束画图
    UIGraphicsEndImageContext();
    [self.view addSubview:imageView];

方式三:使用CAShapeLayer和UIBezierPath设置圆角 : -- 这种方式最好,内存的消耗最少,而且渲染快速

// 创建图片框
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    // 添加图片
    imageView.image = [UIImage imageNamed:@"104.jpg"];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:imageView.bounds.size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
    //设置大小
    maskLayer.frame = imageView.bounds;
    //设置图形样子
    maskLayer.path = maskPath.CGPath;
    imageView.layer.mask = maskLayer;
    [self.view addSubview:imageView];

objectivec 传输安全性阻止了明文HTTP

HTTPS
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>example.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

objectivec 横向多行的UICollectionViewFlowLayout

HorizontallyPageableFlowLayout.h
//
//  HorizontallyPageableFlowLayout.h
//  HTVTest
//
//  Created by QY on 2019/7/10.
//  Copyright © 2019 A-Hing. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface HorizontallyPageableFlowLayout : UICollectionViewFlowLayout

- (instancetype)initWithItemCountPerRow:(NSInteger)itemCountPerRow maxRowCount:(NSInteger)maxRowCount;

@end
HorizontallyPageableFlowLayout.m
//
//  HorizontallyPageableFlowLayout.m
//  HTVTest
//
//  Created by QY on 2019/7/10.
//  Copyright © 2019 A-Hing. All rights reserved.
//

#import "HorizontallyPageableFlowLayout.h"

@interface HorizontallyPageableFlowLayout ()

// 存放全部item布局信息的数组
@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *attributesArray;

// 行数
@property (nonatomic, assign) NSInteger rowCount;
// item每行个数
@property (nonatomic, assign) NSInteger itemCountPerRow;
// item总数
@property (nonatomic, assign) NSInteger itemCountTotal;
// 页数
@property (nonatomic, assign) NSInteger pageCount;
// 最大行数
@property (nonatomic, assign) NSInteger maxRowCount;

@end


@implementation HorizontallyPageableFlowLayout

- (instancetype)initWithItemCountPerRow:(NSInteger)itemCountPerRow maxRowCount:(NSInteger)maxRowCount
{
    self = [super init];
    if (self) {
        self.attributesArray = [NSMutableArray array];
        self.itemCountPerRow = itemCountPerRow;
        self.maxRowCount     = maxRowCount;
        self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    return self;
}

- (void)prepareLayout
{
    [super prepareLayout];
    self.itemCountTotal = [self.collectionView numberOfItemsInSection:0];
    
    // rowCount
    if (self.itemCountTotal == 0) {
        self.rowCount = 0;
    }
    else if ((ceilf(self.itemCountTotal / (float)self.itemCountPerRow)) > self.maxRowCount) {
        self.rowCount = self.maxRowCount;
    }
    else {
        self.rowCount = ceilf(self.itemCountTotal / (float)self.itemCountPerRow);
    }
    
    self.pageCount = self.itemCountTotal ? ceilf(self.itemCountTotal / (float)(self.itemCountPerRow * self.maxRowCount)) : 0;
    
    for (NSInteger i = 0; i < self.itemCountTotal; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexPath];
        [self.attributesArray addObject:attributes];
    }
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger item = indexPath.item;

    /*
     0 2 4 ---\  0 1 2
     1 3 5 ---/  3 4 5 计算转换后对应的item  原来'4'的item为4,转换后为3
     */
    NSInteger page = item / (self.itemCountPerRow * self.maxRowCount);
    // 计算目标item的位置 x 横向偏移  y 竖向偏移
    NSUInteger x = item % self.itemCountPerRow + page * self.itemCountPerRow;
    NSUInteger y = item / self.itemCountPerRow - page * self.rowCount;
    // 根据偏移量计算item
    NSInteger newItem = x * self.rowCount + y;
    NSIndexPath *newIndexPath = [NSIndexPath indexPathForItem:newItem inSection:indexPath.section];

    UICollectionViewLayoutAttributes *newAttributes = [super layoutAttributesForItemAtIndexPath:newIndexPath];
    newAttributes.indexPath = indexPath;
    return newAttributes;
}

- (CGSize)collectionViewContentSize
{
    if (!self.itemCountTotal) {
        return CGSizeMake(0, 0);
    }
    
    return CGSizeMake(self.pageCount * CGRectGetWidth(self.collectionView.frame), 0);
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
    NSMutableArray *array = [NSMutableArray array];

    for (UICollectionViewLayoutAttributes *attr1 in attributes) {
        for (UICollectionViewLayoutAttributes *attr2 in self.attributesArray) {
            if (attr1.indexPath.item == attr2.indexPath.item) {
                [array addObject:attr2];
                break;
            }
        }
    }
    return array;
}

@end

objectivec iOS的获取视频的第一帧图片thumbnailImage

imagePickerController
- (void)imagePickerController:(UIImagePickerController *)picker   didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    if (CFStringCompare ((__bridge CFStringRef) mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo) {
        NSURL *videoUrl=(NSURL*)[info objectForKey:UIImagePickerControllerMediaURL];
        NSString *moviePath = [videoUrl path];
        //这里利用MPMoviePlayerController来获取
        MPMoviePlayerController *player = [[MPMoviePlayerController alloc]initWithContentURL:videoUrl] ;
        UIImage  *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
        
        imageV.image = thumbnail;
        player = nil;//释放player
        
        NSString *videoCacheDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/UploadPhoto/"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:videoCacheDir]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:videoCacheDir withIntermediateDirectories:YES attributes:nil error:nil];
        }
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

objectivec 升级

.m
- (void)upgrade {
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    NSString *url = @"Api/PublicApi/getVersion";
    NSMutableDictionary *params = [NSMutableDictionary new];

    [[[LNNetWorkAPI alloc] initWithUrl:url parameters:params] startWithBlockSuccess:^(__kindof LCBaseRequest *request) {
        [SVProgressHUD dismiss];
        id json = request.responseJSONObject;
        if ([json[@"status"] integerValue] != 1) {
            [SVProgressHUD showInfoWithStatus:json[@"msg"]];
            return;
        }
        
        id data = json[@"data"];
        NSString *version = data[@"version"];
        NSString *version_desc = data[@"version_desc"];
        NSString *version_link = data[@"version_link"];
        
        if ([appVersion compare:version options:NSNumericSearch] == NSOrderedAscending) {
            [self confirmWithTitle:nil message:version_desc confirmText:nil confirmOperation:^{
                [Util openScheme:version_link];
            } cancelText:nil cancelOperation:nil];
        }
        
    } failure:^(__kindof LCBaseRequest *request, NSError *error) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showInfoWithStatus:error.domain];
    }];
}


- (void)checkAppStoreVersion {
    NSString *checkUrlString =@"https://itunes.apple.com/cn/lookup?id=1458709126";
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:checkUrlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            NSLog(@"%@ %@", response, responseObject);
            NSArray *results = [responseObject arrayForKey:@"results"];
            if (results.count) {
                NSDictionary *result = results[0];
                // 版本号
                NSString *version = [result stringForKey:@"version"];
                // 应用名称
                NSString *trackName = [result stringForKey:@"trackName"];
                // 下载地址
                NSString *trackViewUrl = [result stringForKey:@"trackViewUrl"];
                
                NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
                NSString *appVersion = infoDictionary[@"CFBundleShortVersionString"];
                
                if ([appVersion compare:version options:NSNumericSearch] == NSOrderedAscending) {
                    // 更新
                    [self confirm:@"新的版本可以下载,立即更新?" operation:^{
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:trackViewUrl]];
                    }];
                }
            }
        }
    }];
    [dataTask resume];
}

objectivec 创建一个临时变量关联属性

propery
    if ([objc_getAssociatedObject(self, "20190123_joinChannel") isEqualToString:@"alreadyRequest"]) {
        return;
    }
    objc_setAssociatedObject(self, "20190123_joinChannel", @"alreadyRequest", OBJC_ASSOCIATION_RETAIN);