iOS随笔 - 实时更新

1、给 pod 进工程的库添加分类 添加的分类

注意 :创建的分类不能和库文件放在一块,会报 fileNotFound, 需要拖拽到别的文件(pod的东西我们没权限干涉)

2、 RGB颜色表

MIMEType 参考手册

3、Xcode8.0 去除控制台多余打印

选择Product->Scheme->Edit Scheme ...或者直接按 command + shift + < 快捷键,在弹出的窗口中Environment Variables 下添加 OS_ACTIVITY_MODE 设为 disable 。

如图:
4、真机中的所有log日志会被屏蔽掉,原因是ios10 开始为了提高真机性能,所以把log日志屏蔽了

系统的 NSLog() 已经不好使了,如果想在ios10系统的手机上也能打印日志,我们需要用到printf() 替换 NSLog()

#ifndef __OPTIMIZE__
  #define NSLog(...) printf("%f %s\n",[[NSDate date]timeIntervalSince1970],  [[NSString stringWithFormat:__VA_ARGS__]UTF8String]);
#endif
5、Xcode8快速注释无效的解决

解决方法:命令运行 sudo /usr/libexec/xpccachectl
然后必须重启电脑后生效。

6、枚举两种类型
typedef enum {
    //以下是枚举成员 TestA = 0,
    TestB,
    TestC,
    TestD
}Test;//枚举名称
//亦可以如下定义(推荐:结构比较清晰)
typedef NS_ENUM(NSInteger, Test1){
    //以下是枚举成员
    Test1A = 0,
    Test1B = 1,
    Test1C = 2,
    Test1D = 3
};
8 、修改searchbar文字内容及placeholder属性、光标


遍历searchbar的子view,取到TextField文本框,通过修改它的属性完成搜索框的改变.

for (UIView *view in searchBar.subviews){
        for (id subview in view.subviews){
            if ( [subview isKindOfClass:[UITextField class]] ){
       
                //文字大小
                [(UITextField *)subview setFont:[UIFont systemFontOfSize:20]];

                 //placeholder颜色
                NSAttributedString *attri = [[NSAttributedString alloc] initWithString:searchBar.placeholder attributes:@{NSForegroundColorAttributeName: [UIColor purpleColor], NSFontAttributeName: [UIFont systemFontOfSize:13]}];
                [(UITextField *)subview setAttributedPlaceholder:attri];
                
                //修改文本框文字内容颜色
                [(UITextField *)subview setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor]}];
      
                break;
            }
        }
    }
9、修改TextField的placeholder边距

自定义子类TextField,重写- (void)drawPlaceholderInRect:(CGRect)rect;

- (void)drawPlaceholderInRect:(CGRect)rect{
    UIColor *placeholderColor = [UIColor redColor];//设置颜色
    [placeholderColor setFill];
    
    CGRect placeholderRect = CGRectMake(rect.origin.x+30, (rect.size.height- self.font.pointSize)/2, rect.size.width, self.font.pointSize);//设置距离
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineBreakMode = NSLineBreakByTruncatingTail;
    style.alignment = NSTextAlignmentCenter;
    
    NSDictionary *attr = [NSDictionary dictionaryWithObjectsAndKeys:style,NSParagraphStyleAttributeName, self.font, NSFontAttributeName, placeholderColor, NSForegroundColorAttributeName, nil];
    
    [self.placeholder drawInRect:placeholderRect withAttributes:attr];
}
10、利用贝塞尔曲线和CAShapeLayer可以绘制出各种路线

,再配合CAAnimation类的相关动画类即可完成酷炫的动画效果

11、The file “XXX.app” couldn’t be opened because you don’t have permission to view it.

解决方案:http://www.cnblogs.com/gaox97329498/p/4734917.html

12、真机状态cell侧滑失效

注意:需要实现此方法

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{}
13、在xib或storyboard中给label文字换行

需要组合键:option+enter

14、self.view.window属性和代理中window差异

self.view.window 想到了之前的一个面试题,个人感觉此处的window和代理window也没多少差别,打印地址一样。文档解释:This property is nil if the view has not yet been added to a window. 代理中的全局性强,view中的可以临时使用,也差不多少
资料

15、截屏-snapshotViewAfterScreenUpdates

在iOS7 以前, 获取一个UIView的快照有以下步骤: 首先创建一个UIGraphics的图像上下文,然后将视图的layer渲染到该上下文中,从而取得一个图像,最后关闭图像上下文,并将图像显示在UIImageView中。
现在我们只需要一行代码就可以完成上述步骤了:
UIView *snapView = [view snapshotViewAfterScreenUpdates:NO];
返回一个副本view。
截屏可以看这里

16、字典遍历

swift 3.0特别方便

for (key, value) in charDicts {                         //遍历字典
            print("key:\(key), value:\(value)")                 //
        }```
oc中这种方法也很方便

[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"key = %@ and obj = %@", key, obj);
}];```
或者分别遍历字典的[keys]和[values]

for (NSString *s in [dictionary allKeys]) {
    NSLog(@"key: %@", s);
}
17、实现web页面的缩放
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //(initial-scale是初始缩放比,minimum-scale=1.0最小缩放比,maximum-scale=5.0最大缩放比,user-scalable=yes是否支持缩放)
    NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=self.view.frame.size.width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=3.0, user-scalable=yes\""];
    
    [webView stringByEvaluatingJavaScriptFromString:meta];
}
18、网址含中文
- (NSString *)UTF8string:(NSString *)urlPath
{
    NSString *urlString = [urlPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    //iOS10 上边的方法弃用
    if (currentSystemVersion >= 10.0) {
        urlString = [urlPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    return urlString;
}
19、文字属性
CGFloat fontSize = 15.f;
NSString *textString = @"非金融账户仅需要手机号码即可注册。由于并未对您的身份信息进行核实与校验,因此只能体验和使用本App中的部分服务或功能(例如浏览部分基金或资讯),若您需要使用基金交易等高价值服务或功能,您可以选择:";
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 10.f;
    
    // 字号;字体颜色;段落格式(行间距等);字间距
    NSDictionary *attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:fontSize],
                                 NSForegroundColorAttributeName : UIColorFromRGB(0x4a4a4a),
                                 NSParagraphStyleAttributeName : paragraphStyle,
                                 NSKernAttributeName:@1.5f};
    
    NSMutableAttributedString *attributeText = [[NSMutableAttributedString alloc] initWithString:textString attributes:attributes];
    
    CGSize titleSize = [textString boundingRectWithSize:CGSizeMake(CGRectGetWidth(popingView.frame) - padding *2, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    
    UILabel *textLabel = [[UILabel alloc] init];
    textLabel.font = [UIFont systemFontOfSize:fontSize];
    textLabel.frame = CGRectMake(0, 0 , 375, titleSize.height);
    [popingView addSubview:textLabel];
    textLabel.backgroundColor = [UIColor greenColor];
    textLabel.numberOfLines = 0;
    textLabel.attributedText = attributeText;
19、字体UIFont

1.iOS9.0以后系统自带了平方字体PingFangSC,但是在iOS9.0以前,是没有平方字体PingFangSC的,如果我们想用平方字体,在iOS9.0以上是好的,但是在低于9.0的系统上是找不到这个字体的。
UIFont*font = [UIFontfontWithName:@"PingFangSC-Regular"size:18];
需要手动导入第三方字体,代码处理如下:

 //在ios8上是nil,如果不作处理,苹果会帮我们设置默认字体
if(font==nil){
  //这个是我手动导入的第三方平方字体
  font = [UIFontfontWithName:@"PingFang-SC-Regular"size:18];
 }
20、宏使用:这种情况下需要多包装一层
#define NUMBER   10
#define _CALCULATE(A,B)  (A##10##B)
#define CALCULATE(A,B)  \
    _CALCULATE(A,B)
21、 在使用pan gesture拖拽时,注意要在每次计算完拖拽点后清零
- (void)pan:(UIPanGestureRecognizer *)ges
{
    // 获取当前手势的位置
    CGPoint localPoint = [ges translationInView:ges.view];
    NSLog(@"%@", NSStringFromCGPoint(localPoint));
    // 获取到手势view
    UIButton *btn = (UIButton *)[ges view];
    // 计算新的位置坐标
    CGPoint newCenter = CGPointMake(btn.center.x + localPoint.x, btn.center.y + localPoint.y);
    // 更新btn的位置
    btn.center = newCenter;
    // 每次移动完,将移动量置为0,否则下次移动会加上这次移动量
    [ges setTranslation:CGPointZero inView:ges.view];
}
22、 需求:实现在一串字符串中高亮一部分文字并能点击这部分实现相应的功能(超链接,富文本)

比如:

Snip20170421_2.png

方案:UITextView + NSAttributeString富文本 ,(注意禁止掉textview可点击属性和滚动性)

- (void)createAttributeStr
{
    UITextView *_textview = [[UITextView alloc] init];
    _textview.frame = self.view.frame;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"请遵守以下协议《支付宝协议》《微信协议》《建行协议》《招行协议》《中国银行协议》《上海银行协议》"];
    [attributedString addAttribute:NSLinkAttributeName
                             value:@"zhifubao://"
                             range:[[attributedString string] rangeOfString:@"《支付宝协议》"]];
    [attributedString addAttribute:NSLinkAttributeName
                             value:@"weixin://"
                             range:[[attributedString string] rangeOfString:@"《微信协议》"]];
    [attributedString addAttribute:NSLinkAttributeName
                             value:@"jianhang://"
                             range:[[attributedString string] rangeOfString:@"《建行协议》"]];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font] range:NSMakeRange(0, attributedString.length)];
    
    
    UIImage *image = [UIImage imageNamed: @"new_feature_share_true"];
    CGSize size = CGSizeMake(font + 2, font + 2);
    UIGraphicsBeginImageContextWithOptions(size, false, 0);
    [image drawInRect:CGRectMake(0, 2, size.width, size.height)];
    UIImage *resizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
    textAttachment.image = resizeImage;
    NSMutableAttributedString *imageString = [[NSMutableAttributedString alloc] initWithAttributedString:[NSAttributedString attributedStringWithAttachment:textAttachment]];
    [imageString addAttribute:NSLinkAttributeName
                        value:@"checkbox://"
                        range:NSMakeRange(0, imageString.length)];
    [attributedString insertAttributedString:imageString atIndex:0];
    
    _textview.attributedText = attributedString;
    _textview.linkTextAttributes = @{NSForegroundColorAttributeName: [UIColor blueColor],
                                     NSUnderlineColorAttributeName: [UIColor lightGrayColor],
                                     NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
    
    _textview.delegate = self;
    _textview.editable = NO;        //必须禁止输入,否则点击将弹出输入键盘
    _textview.scrollEnabled = NO;
}
#pragma mark --- UITextViewDelegate ----
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    if ([[URL scheme] isEqualToString:@"jianhang"]) {
        NSLog(@"建行支付---------------");
        return NO;
    } else if ([[URL scheme] isEqualToString:@"zhifubao"]) {
        NSLog(@"支付宝支付---------------");
        return NO;
    } else if ([[URL scheme] isEqualToString:@"weixin"]) {
        NSLog(@"微信支付---------------");
        return NO;
    } else if ([[URL scheme] isEqualToString:@"checkbox"]) {
        self.isSelect = !self.isSelect;
        [self protocolIsSelect:self.isSelect];
        return NO;
    }
    return YES;
}
23 、Block:

在mrc下,①只要block内部不引用外部的局部变量,block对象类型都是全局的。②引用了外部局部变量,block就会被分配到栈上。③只有给block变量加上copy才会分配到堆上(只能用copy关键字,使用retain关键字还是在栈上),从而才能被其他地方调用。

在arc下,①只要block引用了外部局部变量,block就会被放到堆上(系统默认调用了copy,但是程序员习惯性还是显示写明),和mac下不同。②block类型多为NSGlobalBlock或者NSMallocBlock,(NSStackBlock不常见,需要强行__weak声明)。

24 、父视图设置alpha值,子视图透明图不受影响
/* 
 1.用一张半透明的图片做背景。
 2.使用colorWithWhite:alpha:类方法
 3.使用colorWithRed:green:blue:alpha:类方法
 4.使用colorWithAlphaComponent:实例方法
 */
25、 performSelector:withObject:afterDelay: 内部大概是怎么实现的,有什么注意事项

创建一个定时器,时间结束后系统会使用runtime通过方法名称(Selector本质就是方法名称)去方法列表中找到对应的方法实现并调用方法

注意事项
调用performSelector:withObject:afterDelay:方法时,先判断希望调用的方法是否存在respondsToSelector:
这个方法是异步方法,必须在主线程调用,在子线程调用永远不会调用到想调用的方法

26、使用AutoLayout后 在ViewDidLoad中打印frame不对

原因:此时的view还没有加载出来,所有的控件的frame都是在当前storyboard中状态,接着才会调用viewWillLayoutSubviews,viewDidLayoutSubviews修改添加的约束
方案:在viewDidLoad中手动添加setNeedsLayout, layoutIfNeeded;
或者在viewWillLayoutSubviews,viewWillAppear中等到frame设置完成的方法里再取frame值

27、issue “file xxx.png is missing from working copy” at project building

适合本人的解决方法:

  • First I Committed and Pushed my changes

Xcode Main Menu > Source Control > Commit

  • Then I Discarded All Changes to get rid of the errors

Xcode Main Menu > Source Control > Discard All Changes

  • After that, the errors stating "file xxx.png is missing from working copy" disappeared.
28、CGContextStrokePath() 、CGContextFillPath () 和 CGContextDrawPath()

当用核心绘图时,eg:给圆环填充颜色,

    CGContextAddArc(context, 100, 60, 50, 0, M_PI * 2, 0);
    CGContextSetLineWidth(context, 10);
    CGContextSetStrokeColorWithColor(context, [UIColor yellowColor].CGColor);
    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
    //* 无效,需要采用下面的 kCGPathFillStroke */
    //CGContextStrokePath(context);
    //CGContextFillPath(context);
    CGContextDrawPath(context, kCGPathFillStroke);

原因:顺序执行完stroke或fill后,会停留在当前结束的点,继续执行下面的fill或stroke只会重复绘制当前点

30、 iOS-数据返回字段null、导致的程序crash问题解决

前提是你用的是AFNetworking第三方。
设置下面属性:

  • serializer.removesKeysWithNullValues = YES;
  • 搜索AFURLResponseSerialization.m类,在定位到AFJSONResponseSerializer类,如下图:

WX20171018-112639.png

参考:iOS-数据返回字段null、导致的程序crash问题解决

31、移除导航条和tabbar黑线
[UITabBar appearance].clipsToBounds = YES;
[UINavigationBar appearance].clipsToBounds = YES;
32、AFN请求报错情况如下
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

afn 默认的解析方式为json,后端返给的可能是非json格式,安卓有可能正常接收,如果在不修改后端数据格式的时候,ios可以通过作如下处理:


WX20171120-100230.png

ps:出现Error Domain=NSCocoaErrorDomain Code=-1060;
afn解析不了html格式的返回,在AFURLResponseSerialization.h里搜索self.acceptableContentTypes,添加上@"text/html",@"text/plain"。 此时可能会报上面的NSCocoaErrorDomain Code=3840错误,在进行如上操作。

33、tableView列表下拉刷新过大导致崩溃

index 3 beyond bounds for empty array

  • 原因:在下拉的时候我们需要请求最新的数据,清空原数组,此时,由于下拉的过大,导致下边的cell移除了屏幕,此时就会调用tableview的代理方法,而此时的数据源却被我们提前清空了,因此导致了数组的越界。
  • 方法:改变清空数组的时机,在请求结束后再remove
34、pop到指定页面popToViewController报Tried to pop to a view controller that doesn't exist.

例如:a->b->c->d, 然后d->a
error情况:

YDWeController *weVC = [YDWeController new];
[self.navigationController popToViewController: weVC animated:YES];

如果想pop到指定的页面需要知道需要a在栈里的位置

YDWeController *weVC = self.navigationController.childViewControllers[0];
[self.navigationController popToViewController: weVC animated:YES];

或者通过遍历

for (UIViewController *controller in self.navigationController.viewControllers) {  
        if ([controller isKindOfClass:[YDWeController class]]) {  
            YDWeController * weVC =(YDWeController *)controller;  
            [self.navigationController popToViewController: weVC animated:YES];  
        }else{  
            [self popToPreviousView];  
        }  
    } 
35、tableview 下回收键盘

一般想到的是touchBegen方法,但是此时无效,因为响应事件的还是vc的view,通过查询资料找到如下三种方法

方法一

方法二

方法三搞个基类
36、navigationBar 的属性 translucent 是否透明

解析default = YES,此时的屏幕尺寸是从最顶端开始计算,如果改成NO,则从导航栏下面开始计算
遇到的案例:在不同的页面入口进入相同的页面,底部会隐藏一定高度,在尝试修改self.edgesForExtendedLayout = UIRectEdgeNone无效后,或者重新计算frame.y是否减64,但是相对麻烦,最后发现是栈底控制器的导航栏的navigationBar.translucent = NO。导致后push的页面都是从导航栏下面开始计算的frame,所以页面少了一截。

37、隐藏状态栏
# step1:  在工程的info.plist文件中, 添加View controller-based status bar appearance-->值为: YES

# step2: 在指定的controller文件中, 实现下面方法

//在试图将要已将出现的方法中
- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
        
        //调用隐藏方法
        [self prefersStatusBarHidden];
        
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
        
    }

}

//实现隐藏方法
- (BOOL)prefersStatusBarHidden{
    
    return YES;
}

注释:info.plist文件中,View controller-based status bar appearance项设为YES,
则View controller对status bar的设置优先级高于application的设置。
为NO则以application的设置为准,view controller的prefersStatusBarHidden方法无效,是根本不会被调用的。
38、版本更新(非后台版)

链接:利用 iTunes 接口检查 App 版本更新

39 、设置富文本后多余文字不显示省略号...

正常情况下UILable 会自动添加..., 当给文字设置了富文本后省略号不会再显示,需要最后重新设置lineBreakMode换行符样式为NSLineBreakByTruncatingTail.
label.lineBreakMode = NSLineBreakByTruncatingTail;

40 返回数据为 :12,@“12”, @“abc” ,非集合类解析时,
    NSString *num=@"\"hah\"";
    NSError *error;
    NSData *createdData = [num dataUsingEncoding:NSUTF8StringEncoding];
    id response=[NSJSONSerialization JSONObjectWithData:createdData options:NSJSONReadingAllowFragments error:&error];
    NSLog(@"Response= %@",response);

NSJSONReadingMutableContainers:返回可变容器,NSMutableDictionary或NSMutableArray。

NSJSONReadingMutableLeaves:返回的JSON对象中字符串的值为NSMutableString

NSJSONReadingAllowFragments:允许JSON字符串最外层既不是NSArray也不是NSDictionary,但必须是有效的JSON Fragment。例如使用这个选项可以解析 @“123” 这样的字符串。参见链接

41、tabbar角标、数字
    self.navigationController.tabBarItem.badgeValue = @"0";
    // 或者
    self.tabBarController.tabBar.items[3].badgeValue = @"0";
42、UILabel 出现黑线

原因:size存在小数(30.213112)
解决:推荐向上取整ceil(),先下取整可能会影响文字显示问题。自行查找相关取整函数。

43、url不更新怎样获取最新图片

1、SDWebImage -> options : refreshCache ;
2、拿到download任务,获取"Last-Modified",并记录lastMo,在requestHeader中添加"If-Modified-Since"字段,value=lastMo

SDWebImageDownloader *imgDownloader=SDWebImageManager.sharedManager.imageDownloader;
imgDownloader.headersFilter  = ^NSDictionary *(NSURL *url, NSDictionary *headers) {
//下载图片成功后的回调
NSFileManager *fm = [[NSFileManager alloc] init];
        NSString *imgKey = [SDWebImageManager.sharedManager cacheKeyForURL:url];
        NSString *imgPath = [SDWebImageManager.sharedManager.imageCache defaultCachePathForKey:imgKey];
        //获取当前路径图片服务端返回的请求头相关信息
        NSDictionary *fileAttr = [fm attributesOfItemAtPath:imgPath error:nil];
        NSMutableDictionary *mutableHeaders = [headers mutableCopy];
        NSDate *lastModifiedDate = nil;
        //大于0则表示请求图片成功
        if (fileAttr.count > 0) {
            if (fileAttr.count > 0) {
                //如果请求成功,则手机端取出服务端Last-Modified信息
                lastModifiedDate = (NSDate *)fileAttr[NSFileModificationDate];
            }
        }
        //格式化Last-Modified
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
        formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        formatter.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss z";
        NSString *lastModifiedStr = [formatter stringFromDate:lastModifiedDate];
        
        lastModifiedStr = lastModifiedStr.length > 0 ? lastModifiedStr : @"";
        
        //设置SDWebImage的请求头If-Modified-Since
        [mutableHeaders setValue:lastModifiedStr forKey:@"If-Modified-Since"];
        return mutableHeaders;
    };
44、ISO8601转本地时间

参考
NSISO8601DateFormatter 默认是0时区(+0000)时间,北京东8区(+08:00)

    NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
    // 处理毫秒级时间
    NSDate *startDate;
    NSString *oldTimeValue = @"2020-06-26T13:00:05.000+0000";
    if ([oldTimeValue containsString:@"."]) {
        NSString *newTimeValue = [oldTimeValue stringByReplacingCharactersInRange:NSMakeRange([oldTimeValue rangeOfString:@"."].location, 4) withString:@""];
        startDate = [formatter dateFromString:newTimeValue];
    } else {
        startDate = [formatter dateFromString:oldTimeValue];
    }
    // 指定时区
    formatter.timeZone = [NSTimeZone systemTimeZone];
    NSString *startTime = [formatter stringFromDate:startDate];
    NSLog(@"dateString = %@", dateString);
    // 结果:dateString = 2020-06-26T21:00:05+08:00
45、masonry、frame 混合使用

纯代码实现自定义布局,我通常使用masonry和设置frame同时进行,然而masonry设置约束后并不能直接反应到frame上.
约束转frame需要时间,设置约束后直接使用frame全部为(0,0,0,0),,如果希望立即生成新的frame需要调用此方法:

[self layoutIfNeeded];// 告知页面需要立即更新

tip: 还是不要混合使用,影响性能

46、UITextView 显示富文本标签
string.append("<p style=\"color:#333333;font-size:14px;font-family:PingFangSC-Semibold\">退订政策</p><p style=\"color:#666666;font-size:12px;font-family:PingFangSC-Regular\">\(cancelPolicyStr)</p>")

47、UIView 的isDescendant

收键盘操作:当UITableView试图中点击非cell的空白也要收键盘效果,scrollview的代理只能滚动时才响应。此时可以考虑添加tap手势,实现tap的代理,拦截点击操作,处理tableview和手势冲突下的响应与否
代码如下:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        for view in collectionView.visibleCells {
            if touch.view?.isDescendant(of: view) == true {  
              // 此时点的是collectionView上的view, tap禁止响应事件
                return false
            }
        }
        return true
    }

tip 或者 常规的判断subviewcontain关系

48、UITextfield rightView位置太靠边缘的问题
// 自定义
//  YGCustomTextField.m
#import "YGCustomTextField.h"
@implementation YGCustomTextField
// 这俩控制文字区域
- (CGRect)textRectForBounds:(CGRect)bounds {
    CGRect superRect = [super textRectForBounds:bounds];
    return CGRectMake(superRect.origin.x, superRect.origin.y, superRect.size.width-8, superRect.size.height);
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
    return [self textRectForBounds:bounds];
}


// 控制rightView位置
- (CGRect)rightViewRectForBounds:(CGRect)bounds {
    CGRect textRect = [super rightViewRectForBounds:bounds];
    textRect.origin.x -= 8;
    return textRect;
}
@end
49、UITableView headerView 自适应

xib上的话,也要约束底部约束,报红没事。纯代码的话更简单,类似。

- (void)awakeFromNib {
    [super awakeFromNib];
    // self 自适应高度
    CGFloat height = [self systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}
50、NSObject中代理不走问题

原因:可能当前对象已经被释放。
解决:创建个单利对象,外部通过单利来调用对象方法

51、UITableViewe 的 tableHeaderView 自适应
if let size = self.tableview.tableHeaderView?.systemLayoutSizeFitting(UIView.layoutFittingExpandedSize) {
   self.historyView.bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
}
51、iOS TableView reloadData刷新列表cell乱跳、tableview闪动的问题。

解决方法:
在iOS 11Self-Sizing自动打开后,contentSize和contentOffset都可能发生改变。可以通过以下方式禁用
self.estimatedRowHeight = 0;
self.estimatedSectionHeaderHeight = 0;
self.estimatedSectionFooterHeight = 0;
————————————————

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335