iOS 小技巧总结

tableview分割线

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
    CGContextFillRect(context, rect);
    
    //上分割线,
    //    CGContextSetStrokeColorWithColor(context, [UIColor colorWithHexString:@"ffffff"].CGColor);
    //    CGContextStrokeRect(context, CGRectMake(5, -1, rect.size.width - 10, 1));
    
    //下分割线
    CGContextSetStrokeColorWithColor(context, UIColorWithRGBA(221, 221, 221, 1).CGColor);
    CGContextStrokeRect(context, CGRectMake(0, rect.size.height, rect.size.width, 1));
}
复制代码

去除cell最后一条分割线

if ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0) {
       cell.separatorInset = UIEdgeInsetsMake(0, -15, 0, -15);
}
if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {//去除cell系统最后一行分割线
       [cell setPreservesSuperviewLayoutMargins:NO];
        
}
复制代码

获取tableView某一组中某一行的Cell

NSIndexPath *resonIndex=[NSIndexPath indexPathForRow:0 inSection:1];
UITableViewCell *cell=[tableView cellForRowAtIndexPath:resonIndex];
复制代码

UIView添加背景图

UIImage *image = [UIImage imageNamed:@”name.png”]; 
view.layer.contents = (id) image.CGImage; 



// 如果需要背景透明加上下面这句 
view.layer.backgroundColor = [UIColor clearColor].CGColor;
复制代码

获取导航栏处于第几层级

NSInteger currentIndex = [self.navigationController.childViewControllers indexOfObject:self];

self.navigationController.viewControllers.firstObject
复制代码

隐藏导航栏

//使用这种方式不仅完美切合滑动返回手势,同时也解决了切换tabBar的时候,导航栏动态隐藏的问题

@interface ViewController ()<UINavigationControllerDelegate>
@end

- (void)viewDidLoad {
    [super viewDidLoad];

    // 设置导航控制器的代理为self
    self.navigationController.delegate = self;
}

#pragma mark - UINavigationControllerDelegate
// 将要显示控制器
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];

    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}

- (void)dealloc {
    self.navigationController.delegate = nil;
}
复制代码

先返回首页再跳转tabbar

self.tabBarController.selectedIndex=[data[@"index"] integerValue];
[self.navigationController popToRootViewControllerAnimated:NO];
复制代码

返回按钮设置

//返回某一级
NSArray *array = self.navigationController.viewControllers;
[self.navigationController popToViewController:array[1] animated:YES];
//返回上上级
int index = (int)[[self.navigationController viewControllers]indexOfObject:self];
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:(index -2)] animated:YES];
复制代码

销毁页面 push新页面的同时销毁当前页面

if ([self.navigationController.childViewControllers indexOfObject:self]!=0) {
     NSMutableArray *vcs = [self.navigationController.viewControllers mutableCopy];
     for (UIViewController *vc in self.navigationController.viewControllers) {
         if ([vc isKindOfClass:[self class]] ) {
             [vcs removeObject:vc];
         }
     }
     self.navigationController.viewControllers=vcs;
}

复制代码

cell复用防止重复加载/移除所有视图控件

for(UIView *view in cell.subviews){
    if(view){
        [view removeFromSuperview];
     }
}
复制代码

cell高度缓存

@property (nonatomic, strong) NSMutableDictionary *heightAtIndexPath;//缓存高度所用字典

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSNumber *height = [self.heightAtIndexPath objectForKey:indexPath];
    if(height)
    {
        return height.floatValue;
    }
    else
    {
        return 100;
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSNumber *height = @(cell.frame.size.height);
    [self.heightAtIndexPath setObject:height forKey:indexPath];
}
复制代码

cell侧滑返回自定义添加图片

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
//如果想在侧拉的时候显示是中文的删除,只需要用下面的方法替换掉上面的方法就好了
-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewRowAction *deleteRoWAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){//title可自已定义
       
    }];
    return @[deleteRoWAction];
}


//iOS11之后侧滑删除-支持设置图片【设置后iOS11优先走这里,与上面不冲突】
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath  API_AVAILABLE(ios(11.0)){
    //删除
    UIContextualAction *deleteRowAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"delete" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        
        DLog(@"delete")
        completionHandler (YES);
    }];
    deleteRowAction.image = [UIImage imageNamed:@"favor_remove"];
    deleteRowAction.backgroundColor = [UIColor whiteColor];

    UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[deleteRowAction]];
    return config;
}
复制代码

监听页面侧滑返回

- (void)didMoveToParentViewController:(UIViewController *)parent{
    [super didMoveToParentViewController:parent];
    if(!parent){
        //侧滑返回页面时间
    }
}
复制代码

移除所有子视图

[view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
复制代码

获取控件在父视图上的坐标尺寸

UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
CGRect rect=[testView convertRect:testView.bounds toView:window];
复制代码

价格有小数且不为0则显示几位小数 没有则显示整数

- (NSString *)formatPriceWithFloat:(float)price {
    if (fmodf(price, 1)==0) {
        return [NSString stringWithFormat:@"%.0f",price];
    } else if (fmodf(price*10, 1)==0) {//如果有一位小数点
        return [NSString stringWithFormat:@"%.1f",price];
    } else {//如果有两位小数点
        return [NSString stringWithFormat:@"%.2f",price];
    }
}
复制代码

fmod()详解

给视图添加渐变色

CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = @[(__bridge id)[UIColor colorWithHexString:@"#656565"].CGColor, (__bridge id)[UIColor colorWithHexString:@"#2B2829"].CGColor];
//  设置颜色变化点,取值范围 0.0~1.0
gradientLayer.locations = @[@0.0, @1.0];
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(0, 1);
gradientLayer.frame = bkView.bounds;
[bkView.layer addSublayer:gradientLayer];
复制代码

排序

NSMutableArray *array = [NSMutableArray arrayWithObjects:@"5",@"3",@"4",@"2",nil];

    

// 倒序

NSMutableArray *resultArr = (NSMutableArray *)[[array reverseObjectEnumerator] allObjects];

NSLog(@"倒序:%@",resultArr); // 倒序的结果为:2,4,3,5

    

// 升序

[array sortUsingSelector:@selector(compare:)];

NSLog(@"升序:%@",array); // 升序的结果为:2,3,4,5

    

// 降序

NSEnumerator *enumerator = [array reverseObjectEnumerator];

NSMutableArray *downArr = (NSMutableArray *)[enumerator allObjects];

NSLog(@"降序:%@",downArr); // 降序的结果为:5,4,3,2

复制代码

通过字号和文案计算宽度

//通过字号和文案计算宽度
- (CGSize)completeTextWidthWithFont:(CGFloat)fontSize text:(NSString *)text{
    NSDictionary *attrs = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:fontSize]};
    CGSize size = [text sizeWithAttributes:attrs];
    return size;
}
复制代码

字符串转变为字典

NSString * str  = @"{key:value}";
NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
复制代码

视图手势移动

- (void)move:(UIPanGestureRecognizer *)panGesture {
    if (panGesture.state == UIGestureRecognizerStateChanged) {
        UIView *subview = panGesture.view;
        CGPoint point = [panGesture translationInView:self.superview];
        CGFloat centerX = subview.centerX + point.x;
        CGFloat centerY = subview.centerY + point.y;
        
        CGFloat left = subview.width / 2.0;
        CGFloat right = self.superview.width - subview.width / 2.0;
        CGFloat top = STATUS_NAVI_HEIGHT + subview.height / 2.0;
        CGFloat bottom = self.superview.height - subview.height / 2.0 - TABBAR_HEIGHT;
        if (centerX < left) centerX = left;
        if (centerX > right) centerX = right;
        if (centerY < top) centerY = top;
        if (centerY > bottom) centerY = bottom;
        
        subview.center = CGPointMake(centerX, centerY);
        [panGesture setTranslation:CGPointZero inView:self.superview];
    }else if (panGesture.state == UIGestureRecognizerStateEnded){
        UIView *subview = panGesture.view;
        CGPoint point = [panGesture translationInView:self.superview];
        CGFloat centerX = subview.centerX + point.x;
        CGFloat centerY = subview.centerY + point.y;

        CGFloat supCenterX = self.superview.width/2.0;
        CGFloat top = STATUS_NAVI_HEIGHT + subview.height / 2.0;
        CGFloat bottom = self.superview.height - subview.height / 2.0 - TABBAR_HEIGHT;

        if (centerX < supCenterX){
            centerX = subview.width / 2.0;
        }else{
            centerX = self.superview.width - subview.width / 2.0;
        }
        if (centerY < top) centerY = top;
        if (centerY > bottom) centerY = bottom;

        subview.center = CGPointMake(centerX, centerY);
        [panGesture setTranslation:CGPointZero inView:self.superview];
    }
}
复制代码

统一单例

+ (instancetype)sharedInstance {
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}


+ (instancetype)shared<#Manager#>
{
    static <#managerClass#> *shareManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareManager = [[<#managerClass#> alloc] init];
    });
    return shareManager;
}
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享