基于UIView约束更新UITableView大小

问题描述:

我有一个UIView,里面有一个UITableView。基于UIView约束更新UITableView大小

在一个UIViewController,我实例UIView的是这样的:

viewMain = [ViewMain alloc]initwithframe:cgrectmake(0,0,200,500)]; 

这里面视图,在该方法initWithFrame:方法(的CGRect)帧,我实例化的UITableView这样的:

_tableView = [UITableView alloc]iniWithFrame:CGRectMake(0,0,frame.size.width,frame.size.height)]; 

问题是当我将约束应用于viewMain时,如何根据viewMain布局约束更新tableView的de尺寸?

你需要限制添加到childview(即自动版式本身,如果上海华盈的改变),像这样:

NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:viewMain attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:_tableView attribute:NSLayoutAttributeLeft multiplier:1 constant:0]; 
[_tableView addConstraint:left]; 

NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:viewMain attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_tableView attribute:NSLayoutAttributeTop multiplier:1 constant:0]; 
[_tableView addConstraint:top]; 

NSLayoutConstraint *width = [NSLayoutConstraint constraintWithItem:viewMain attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:_tableView attribute:NSLayoutAttributeWidth multiplier:1 constant:0]; 
[_tableView addConstraint:width]; 

NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:viewMain attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:_tableView attribute:NSLayoutAttributeHeight multiplier:1 constant:0]; 
[_tableView addConstraint:height]; 

不知道你是否也需要这样做:

_tableView.translatesAutoresizingMaskIntoConstraints = NO; 

在添加约束之前。

如果您使用框架设置表格视图,那么您将无法使用约束来更新布局。如果您想根据您的父视图更新您的表格视图,请使用故事板中的约束来更新约束。

基本上你必须在-tableView:cellForRowAtIndexPath:的单元格上调用​​和-updateConstraintsIfNeeded

请参阅this answer中的非常详细的说明和示例代码。

这是一个很棒的Tutorial by Ray Wenderlich

你也可以在你的tableViewController试试这个:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (IS_IOS8_OR_ABOVE) { 
     return UITableViewAutomaticDimension; 
    } 

    //self.prototypeCell.bounds = CGRectMake(0, 0, CGRectGetWidth(self.tableView.bounds), CGRectGetHeight(self.prototypeCell.bounds)); 

    [self configureCell:self.prototypeCell forRowAtIndexPath:indexPath]; 

    [self.prototypeCell updateConstraintsIfNeeded]; 
    [self.prototypeCell layoutIfNeeded]; 

    return [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height; 
} 

我将设置的tableView的帧等于MAINVIEW的框架。 ,即:

_tableView = [UITableView alloc]iniWithFrame:CGRectMake(mainView.frame.origin.x,mainView.frame.origin.y,mainView.frame.size.width,mainView.frame.size.height)];