iOS学习征服iOSiOS Developer

iOS开发中遇到的坑

2017-08-26  本文已影响109人  life白玉兰

从事iOS开发已有数年,一路走来踩过无数的坑,然而都踩过哪些坑,如今想来脑子里竟是一片空白,为什么呢?仔细想了想,其一,当初踩坑时经验欠缺,所以遇到的坑大多在经验多起来以后就算不得坑了;其二,踩过的坑只遇到过一次或者两次,事后又没记录,久而久之早已忘得干干净净了。在本篇文章中我会陆续记录下开发中遇到的一些坑,给自己做个记录,也希望可以帮到有需要的同学。

1.为UITableView设置tableHeaderView在iOS 10以下出现遮挡

UITableView作为一个使用率很高的控件,相信很多同学对它都不陌生,不知道有多少同学使用过它的tableHeaderView属性来为它设置头视图呢?如果有的话,不知道大家踩没踩过下边这个坑:
先看代码:

#import "ViewController.h"

@interface ViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, weak) UITableView *tableView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15);
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor redColor];
    tableView.tableHeaderView = headerView;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.tableView.frame = self.view.bounds;
    self.tableView.tableHeaderView.frame = CGRectMake(0, 0, self.tableView.frame.size.width, 150);
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"UITableViewCellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"这是第%ld个cell", indexPath.row];
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

当运行在iOS 10时如下:

iOS 10

很正常对不对?然后运行在iOS 9看一下:

iOS 9

这回我们发现cell几乎是从第4个才开始显示出来,前面的cell貌似被盖住了,为了验证我们看下图层:


图层

果然tableHeaderView盖住了最上边的几个cell,经测试iOS 10以下都会出现这种情况,原因至今未明,如果有知道的还请赐教!

解决方法

这个坑的解决方法也简单,我只需要在上面代码中其中headerView的创建时给它一个高度值就OK了:
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 150)];
这里就不贴图了,大家可以自己验证去!

2. UITableView的分割线显示位置偏移

我相信这个问题很多人都遇到过,我曾碰到过有人为了解决这个问题而把
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

然后又在自定义的cell里在cell最下方加一个view来充当分割线,其实如果想修正分割线偏移不用这么麻烦,可以用下面的方法:
tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15);

四个参数分别为:上、左、下、右,需求不奇葩的情况下,足够满足你的所需了

待续。。。

上一篇 下一篇

猜你喜欢

热点阅读