iOS开发过程中的小 tips

之前在做项目的时候经常会遇到一些细小的知识点,不影响做项目的大方向,但确影响了很多细小的点..比如公式转换,汉字拼音,颜色转换等等,什么都涉及...上次写的还是在CSDN写blog时记录的:iOS开发 容易犯错的知识点和不错的细小知识点(持续更新),现在换地方了,就不在接着原来的写了,重开一个,依旧持续更新/记录.

35.当你向项目中添加一个文件夹时,往往会面对Create groupsCreate folder references的选择

前者Create groups for any added folders  : 给任一你添加的文件创建一个组groups
后者Create folder references for any added folders  :给任一你添加的文件创建一个文件夹folder
两的区别是:前者的文件夹是黄色的;后者的文件夹是蓝色的
如果有一个info.h文件需要引用:前者直接导入import "info.h"就可能使用;后者你需要import "文件夹名字/info.h"才可能使用,否则编译时找不到文件info.h。

36.Pointer is missing a nullability type specifier (__nonnull or __nullable)的解决方法:

首尾加入NS_ASSUME_NONNULL_BEGINNS_ASSUME_NONNULL_END

37.UIButton文本对齐问题

这里使用button.titleLabel.textAlignment = NSTextAlignmentLeft;这行代码是没有效果的,这只是让标签中的文本左对齐,但并没有改变标签在按钮中的对齐方式.
所以,我们首先要使用button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; 这行代码,把按钮的内容(控件)的对齐方式修改为水平左对齐,但是这们会紧紧靠着左边,不好看...
所以我们还可以修改属性:button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);这行代码可以让按钮的内容(控件)距离左边10个像素,这样就OK了

38.获取window的方法之前都是直接[UIApplication sharedApplication].keyWindow;

之后导入bug tags的时候提醒用比较严谨的获取方法

- (UIWindow *)lastWindow
{
    NSArray *windows = [UIApplication sharedApplication].windows;
    for(UIWindow *window in [windows reverseObjectEnumerator]) {
         
        if ([window isKindOfClass:[UIWindow class]] &&
            CGRectEqualToRect(window.bounds, [UIScreen mainScreen].bounds))
             
            return window;
    }
     
    return [UIApplication sharedApplication].keyWindow;
}

39.延长LaunchImage的显示时间

如果你觉得你开启太快,那么漂亮得LaunchImage还没怎么展示就跳过了.你可以在你的第一个加载页面中添加如下代码来
NSThread.sleepForTimeInterval(3.0)//延长3秒

40.关闭键盘的自动联想和首字母大写功能

[_userNameTextField setAutocorrectionType:UITextAutocorrectionTypeNo];
[_userNameTextField setAutocapitalizationType:UITextAutocapitalizationTypeNone];

41.设置导航栏下方不显示内容(此时导航栏无透明度)

self.extendedLayoutIncludesOpaqueBars = YES;

42.监测键盘通知时,发送多次的解决情况

typedef NS_ENUM(NSInteger, KeyBoardAction) {
    KeyBoardActionShow = 0,
    KeyBoardActionHide = 1
}

self.action = 0;
// Do any additional setup after loading the view, typically from a nib.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(show) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hide) name:UIKeyboardWillHideNotification object:nil];


- (void)show {
    // 防止按home键退出后台再返回前台发送的多余通知
    if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) {
        return;
    }
    if (_action == KeyBoardActionShow) {
        NSLog(@" name = %s",__FUNCTION__);
        _action = KeyBoardActionHide;
    }
}

- (void)hide {
    if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) {
        return;
    }
    if (_action == KeyBoardActionHide) {
        NSLog(@" name = %s",__FUNCTION__);
        _action = KeyBoardActionShow;
    }
}

43.http/https请求获取cookie的问题

项目需要获取cookie,但是网上找的获取cookie的方法:

NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [cookieJar cookies]) {
   NSLog(@"%@", cookie);
}

无法获取完整的cookie,打印出来的只有一小部分....实际获取的方法是:
NSString *cookieString = [[request.requestOperation.response allHeaderFields ] valueForKey:@"Set-Cookie"];

44.金融产品的金额形式变化

// 30000000 - > 30,000,000
- (NSString *)addMarkToString {
    NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setFormatterBehavior: NSNumberFormatterBehavior10_4];
    [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
    NSString *numberString = [numberFormatter stringFromNumber: [NSNumber numberWithInteger: self.intValue]];
    return numberString;
}

+(NSString *)countNumAndChangeformat:(CGFloat)num
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init] ;
    [numberFormatter setPositiveFormat:@"###,##0.00;"];
    NSString *formattedNumberString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:num]];
    return formattedNumberString;
}

45.iOS中使用blend改变图片颜色

// UIImage Category
- (UIImage *) imageWithTintColor:(UIColor *)tintColor blendMode:(CGBlendMode)blendMode
{
    //We want to keep alpha, set opaque to NO; Use 0.0f for scale to use the scale factor of the device’s main screen.
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
    [tintColor setFill];
    CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
    UIRectFill(bounds);
    
    //Draw the tinted image in context
    [self drawInRect:bounds blendMode:blendMode alpha:1.0f];
    
    if (blendMode != kCGBlendModeDestinationIn) {
        [self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
    }
    
    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return tintedImage;
}

喵神有篇文章讲这个的->iOS中使用blend改变图片颜色

46.tableView的分割线左边不到头的问题

tableView.separatorInset = UIEdgeInsetsZero
tableView.layoutMargins = UIEdgeInsetsZero
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        cell.separatorInset = UIEdgeInsetsZero
        cell.layoutMargins = UIEdgeInsetsZero
        cell.preservesSuperviewLayoutMargins = false
    }

47.实现UITableView Plain SectionView和table不停留一起滑动

1) 这个代码是通过scroll偏移量来监听和改变你的tableview的contentInset 可见很不好(试试就知道) X

   // 去掉UItableview headerview黏性(sticky)
    - (void)scrollViewDidScroll:(UIScrollView *)scrollView
    {
        CGFloat sectionHeaderHeight = 40;(你的section高度)
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        }
        else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }

2)和第一个没太大本质区别,在自定义headSectionView中重写setframe方法来重载table的sectionTablePlainSectionView

- (void)setFrame:(CGRect)frame{
    CGRect sectionRect = [self.tableView rectForSection:self.section];
    CGRect newFrame = CGRectMake(CGRectGetMinX(frame), CGRectGetMinY(sectionRect), CGRectGetWidth(frame), CGRectGetHeight(frame)); [super setFrame:newFrame];
}

3)不推荐使用Plain style,改用 Group style, 只需要将 footerSectionHeight 设置为0.01(不是固定的,保证很小就行), HeaderSectionHeight按照实际需求高度多少设置就行,一样可以实现 Plain style 的效果

48.Swift 沙盒路径集合

// MARK: - 沙盒路径集合
// http://stackoverflow.com/questions/32501627/stringbyappendingpathcomponent-is-unavailable
// http://stackoverflow.com/questions/32120581/stringbyappendingpathcomponent-is-unavailable
extension String {
    var lastPathComponent: String {
        return (self as NSString).lastPathComponent
    }
    
    var pathExtension: String {
        return (self as NSString).pathExtension
    }
    
    var stringByDeletingLastPathComponent: String {
        return (self as NSString).stringByDeletingLastPathComponent
    }
    
    var stringByDeletingPathExtension: String {
        return (self as NSString).stringByDeletingPathExtension
    }
    
    var pathComponents: [String] {
        return (self as NSString).pathComponents
    }
    
    func stringByAppendingPathComponent(path: String) -> String {
        let nsSt = self as NSString
        return nsSt.stringByAppendingPathComponent(path)
    }
    
    func stringByAppendingPathExtension(ext: String) -> String? {
        let nsSt = self as NSString
        return nsSt.stringByAppendingPathExtension(ext)  
    }  
}

49.用hidesBottomBarWhenPushed属性实现隐藏BottomBar时候的的几个坑!

在创建好后,马上调用 vc.hidesBottomBarWhenPushed = true
下面有几个新手常掉进去的坑:
1.不能够在viewDidLoad() 方法里调用, 一定要在viewDidLoad加载之前  也就是 push之前调用:
2.区分下面两个方法
    A -> hidesBottomBarWhenPushed = true
    B -> self.navigationController?.hidesBottomBarWhenPushed = true  这个方法会因为没有被push前,就没有navigationController, 所以设置无效

50.UIViewcontroller的title

// will set the title of a navigationBar and also cause the title to cascade down to a UITabBarItem, if present.
self.title = @"Your title";

// will only set the title of the navigationBar, assuming a UINavigationController is present, and NOT affect a UITabBarItem.
self.navigationItem.title = @"Your title";  

// will set the title of a UITabBarItem but NOT the UINavigationBar.
self.navigationController.title = @"Your title";

51.memory-leak-when-using-wkscriptmessagehandler

http://stackoverflow.com/questions/31094110/memory-leak-when-using-wkscriptmessagehandler

52. UIScrollView 的 autolayout

Storyboard中,如果父视图是 UIScrollView, 在它上面不要直接绘制各个子控件, 应该先拖一个UIView约束为(0,0,0,0),再到这个 view 上去绘制.

你可能感兴趣的:(iOS开发过程中的小 tips)