OC 相对布局

版权声明:本文为博主原创文章,转载请标明地址。 https://blog.csdn.net/u013034413/article/details/79409845

页面里一个UITableView,然后UITableView下面有一个Button,想要实现的效果,当UITableView的高度改变时,保证Button和UITableView的竖直间距不变。
这里写图片描述

实现:
给UITableView设置高度约束,给一个默认的高度值160(因为这里初始化显示4个cell,每个高度40),然后control到 ViewController里面去,动态修改UITableView的高度约束值即可。
这里写图片描述

#import "HomeArticleViewController.h"
@interface HomeArticleViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *h;

@end
CGRect frame;
@implementation HomeArticleViewController
NSInteger k=4;//默认显示4个cell
//button点击事件,点击后修改cell个数为6,高度约束变为6*240,tableView重新加载数据
- (IBAction)load:(id)sender {
    k=6;
    _h.constant = 6*40;
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _tableView.delegate = self; //代理
    _tableView.dataSource = self;
//    //背景颜色
    _tableView.backgroundColor = [UIColor blackColor];
}


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

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return k;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:indexPath.row%2==0 ? @"ID1" : @"ID2"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: @"ID1"];
            cell.contentView.backgroundColor = [UIColor redColor];
    }
    //cell选中效果
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.text = @"test";
    cell.textLabel.textColor = [UIColor whiteColor];

    return cell;
}

//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //    indexPath.section
    //    indexPath.row

    return 40;
}
@end

猜你喜欢

转载自blog.csdn.net/u013034413/article/details/79409845