iOS开发过程中积累的一些小方法

1、去掉UITableView没有内容显示的cell

self.tableView.tableFooterView = [UIView new];

2、修改UITableView自带的线条(颜色和位置)

//ios8 设置UITableViewCell左侧默认15像素的空白
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
    [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    [self.tableView setSeparatorColor:SC_TABLEVIE_LINELIGTHT];
}
if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
    [self.tableView setLayoutMargins:UIEdgeInsetsZero];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

3、约束动画实现

    self.shareBtnBgTopConstraint.constant = -102;
    // 告诉约束需要更新
    [self.shareBtnBgView setNeedsUpdateConstraints];
    // 调用此方法告诉检测是否需要更新约束,若需要则更新,下面添加动画效果才起作用
    [self.shareBtnBgView updateConstraintsIfNeeded];
    [UIView animateWithDuration:0.5 animations:^{
        self.shareView.alpha = 0.6;
        [self.view layoutIfNeeded];
    }];

4、单例实现方法

+ (HttpRequestEngine *)shareInstance{
    static HttpRequestEngine *httpEngine = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        httpEngine = [[HttpRequestEngine alloc] init];
    });
    return httpEngine;
}

5、AFNetWorking监听网络变化

#pragma mark - 监听网络变化
- (void)buggedNetWorkChange{
    AFNetworkReachabilityManager *afNetworkReachabilityManager = [AFNetworkReachabilityManager sharedManager];
    [afNetworkReachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:{
                NSLog(@"无网络");
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi:{
                NSLog(@"WiFi网络");
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWWAN:{
                NSLog(@"2G/3G/4G网络");
                break;
            }
            default:
                break;
        }
    }];
    [afNetworkReachabilityManager startMonitoring];
}

【6】UITextField占位文字的颜色的修改(.h和.m文件实现)

@interface UITextField (PHColor)

/**
 *  占位文字颜色
 */
@property (strong, nonatomic) UIColor *placeholderColor;

@end
@implementation UITextField (PHColor)

- (void)setPlaceholderColor:(UIColor *)placeholderColor{
    BOOL change = NO;
    if (self.placeholder == nil) {
        self.placeholder = @" ";
        change = YES;
    }
    [self setValue:placeholderColor forKeyPath:@"placeholderLabel.textColor"];
    if (change) {
        self.placeholderColor = nil;
    }
}

- (UIColor *)placeholderColor{
    return [self valueForKey:@"placeholderLabel.textColor"];
}

@end

【7】iOS导航栏NavigationBar设置透明,以及添加变色的动画
透明只需设置NavigationBar的背景图片为一张空图片即可

[self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];

NavigationBar下边有一个ShadowImage,也可以通过设置空的UIImage设置透明

[self.navigationController.navigationBar setShadowImage:[UIImage new]];

变色动画,在NavigationBar下插入一个view,执行动画改变这个view的透明度即可。

CGRect frame = self.navigationController.navigationBar.frame;
_alphaView = [[UIView alloc] initWithFrame:CGRectMake(0, -20, frame.size.width, frame.size.height+20)];
_alphaView.backgroundColor = [UIColor greenColor];
_alphaView.userInteractionEnabled = NO;
[self.navigationController.navigationBar insertSubview:_alphaView atIndex:0];

【8】iOS 实现ScrollView 上滑隐藏Navigationbar,下滑显示

#pragma mark 滑动隐藏导航栏
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    if (velocity.y>0) {
        [self.navigationController setNavigationBarHidden:YES animated:YES];
    }else {
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
}

【9】去掉UIWebView中弹框的alertView的title
Js中有Alert、confirm和promopt三种类似iOS本地的UIAlertView 样子,但是在iOS的app中弹出alertView的title是url地址,不怎么美观,可以用以下方法解决:

///新建一个UIWebView的扩展类,然后在用到webView的类里引用头文件就OK了
@interface UIWebView (JavaScripAlert) 

- (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame;

- (BOOL)webView:(UIWebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame;

@end
@implementation UIWebView (JavaScripAlert)

static BOOL status = NO;
static BOOL isEnd =NO;

- (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame {
    
    UIAlertView* customAlert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                         message:message
                                                        delegate:nil
                                               cancelButtonTitle:@"确定"
                                               otherButtonTitles:nil];
    
    [customAlert show];
}

- (NSString *) webView:(UIWebView *)view runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(id)frame {
    return @"";
}

- (BOOL)webView:(UIWebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame {
    UIAlertView *confirmDiag = [[UIAlertView alloc] initWithTitle:@"提示"
                                                          message:message
                                                         delegate:self
                                                cancelButtonTitle:@"取消"
                                                otherButtonTitles:@"确定",nil];
    
    [confirmDiag show];
    CGFloat version = [[[UIDevice currentDevice] systemVersion]floatValue];
    if (version >= 7.) {
        while (isEnd == NO) {
            [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01f]];
            
        }
    }else {
        while (isEnd ==NO && confirmDiag.superview !=nil) {
            [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01f]];
        }
    }
    isEnd = NO;
    return status;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    status = buttonIndex;
    isEnd = YES;
}

@end

【10】获取磁盘总空间大小

+ (CGFloat)diskOfAllSizeMBytes  {
    CGFloat size = 0.0;
    NSError *error;
    NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
    if (error) {
#ifdef DEBUG
        NSLog(@"error: %@", error.localizedDescription);
#endif
    }else{
        NSNumber *number = [dic objectForKey:NSFileSystemSize];
        size = [number floatValue]/1024/1024;
    }
    return size;
}

获取磁盘可用空间大小

+ (CGFloat)diskOfFreeSizeMBytes{
    CGFloat size = 0.0;
    NSError *error;
    NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
    if (error) {
#ifdef DEBUG
        NSLog(@"error: %@", error.localizedDescription);
#endif
    }else{
        NSNumber *number = [dic objectForKey:NSFileSystemFreeSize];
        size = [number floatValue]/1024/1024;
    }
    return size;
}

【11】判断字符串中是否含有中文

+ (BOOL)isHaveChineseInString:(NSString *)string {
    for(NSInteger i = 0; i < [string length]; i++){
        int a = [string characterAtIndex:i];
        if (a >= 0x4e00 && a < 0x9fff) {
            return YES;
        }
    }
    return NO;
}

【12】Xcode调试:
a、快速定位约束冲突方法:

添加UIViewAlertForUnsatisfiableConstraints的断点
iOS开发过程中积累的一些小方法_第1张图片

b、常用调试断点

[NSException raise]
objc_exception_throw
iOS开发过程中积累的一些小方法_第2张图片

【13】当遇到一些老古董设备的时候,程序运行出现以下错误:

dyld: Library not loaded: /System/Library/Frameworks/Contacts.framework/Contacts
  Referenced from: /private/var/mobile/Containers/Bundle/Application/90A475A5-8EC4-416A-A354-0401D1CF5152/Butler.app/Butler
  Reason: image not found

解决办法:
Project-> Targets-> Build Phases-> Link Binary with Libraries
设置 Contacts.framework 的 status 为 Optional 搞定!

【14】UITableViewCell处于选中状态下,UIView的背景颜色消失的解决办法:

/// 在cell的以下两个方法里重新设置view的背景颜色
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    self.pointView.backgroundColor = SC_TEXT_GREEN_COLOR;
}

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
    [super setHighlighted:highlighted animated:animated];
    self.pointView.backgroundColor = SC_TEXT_GREEN_COLOR;
}

待续,持续完善...

你可能感兴趣的:(iOS开发过程中积累的一些小方法)