2014-11-24 65 views
0

我有一個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尺寸?

回答

1

你需要限制添加到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; 

在添加約束之前。

0

如果您使用框架設置表格視圖,那麼您將無法使用約束來更新佈局。如果您想根據您的父視圖更新您的表格視圖,請使用故事板中的約束來更新約束。

0

基本上你必須在-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; 
} 
0

我將設置的tableView的幀等於MAINVIEW的框架。 ,即:

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