设置tableView固定位置和尺寸---automaticallyAdjustsScrollViewInsets

来源:互联网 发布:关于大数据营销的案例 编辑:程序博客网 时间:2024/06/07 03:16

最近在做项目的时候遇到了一个令人郁闷的问题,我想在ViewController里添加一个tableView,并把tableView设置

一个固定的尺寸和位置时,发现结果并不是我所预料的那样,为什么cell的顶部没有于tableView的顶部对齐呢,

这是个很令人郁闷的问题啊

为了能够看出明显的效果,这里我设置ViewController的背景色为蓝色,设置tableView的背景色为黄色,而

cell的背景颜色默认的为白色,并设置了四条数据,并固定了每个cell的高度

//创建tableView并设置tableView在Controller上的尺寸和位置- (void)createTableView{    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 200, ScreenWidth, 260) style:UITableViewStylePlain];        self.tableView.backgroundColor = [UIColor yellowColor];        self.tableView.dataSource = self;    self.tableView.delegate = self;        [self.view addSubview: self.tableView];}

结果如下:

             

怎么会这样呢,查找了很多的资料,也看了一些官方的API后发现,在ios7 Controller新增了一些属性

@property(nonatomic,assign) BOOL automaticallyAdjustsScrollViewInsets NS_AVAILABLE_IOS(7_0); // Defaults to YES

<span style="font-family: 'PingFang SC'; background-color: rgb(255, 255, 255);">按照字面的解释应该是:自动适应scrollView的Insets并且它的默认值是YES,</span><span style="font-family: 'PingFang SC'; line-height: normal;">如果你不想让</span><span style="line-height: normal; font-family: Arial;">scroll view</span><span style="font-family: 'PingFang SC'; line-height: normal;">的内容自动调整,</span>

将这个属性设为NO(默认值YES)自动调整scrollView的inset,设置为NO,不让ViewController调整,我们自己修改布局

- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view.    self.view.backgroundColor = [UIColor blueColor];    self.navigationItem.title = @"个人中心";    //设置为NO,取消系统默认的布局,我们可以自己对ViewController布局    self.automaticallyAdjustsScrollViewInsets = NO;        [self createTableView];}
再次运行我们的程序发现这才是我们预想的效果:



当然读者可以自己尝试一下,我们平时往ViewController里添加tableView时,都是填充整个viewController,

//创建tableView并设置tableView在Controller上的尺寸和位置- (void)createTableView{    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];        self.tableView.backgroundColor = [UIColor yellowColor];        self.tableView.dataSource = self;    self.tableView.delegate = self;        [self.view addSubview: self.tableView];}
结果如下:


如果在- (void)viewDidLoad内添加

//设置为NO,取消系统默认的布局,我们可以自己对ViewController布局    self.automaticallyAdjustsScrollViewInsets = NO;
你会发现这并不是我们所要的结果:


此时你会发现,我们的tableView被NavigationController遮住了

self.automaticallyAdjustsScrollViewInsets = NO;

看到这里你应该就会明白什么了吧。此属性默认为YES,这样ViewController下如果只有一个scollView或者其子类,那么

会自动留出空白,让scrollView滚动经过各种bar下时能隐约看到内容。如果我们要想自己设置tableView的尺寸和位置就需要

将此属性设置为NO,自己去控制留白一极坐标的问题


1 0
原创粉丝点击