2013-10-14 32 views
1

我有一個容器視圖:表視圖中消失時,我添加約束

1

和我有我添加到容器編程表視圖:

self.searchResultsSourcesTVC = [storyboard instantiateViewControllerWithIdentifier:@"searchResultsSourcesTVC"];  
[self.searchResultsContainer addSubview:self.searchResultsSourcesTVC.view]; 

結果這裏是表格視圖不會自動調整大小以適應容器;它似乎向屏幕南部延伸了很長一段時間,以至於滾動條可以完全消失在屏幕以南。但它確實顯示錶格和搜索結果。

所以我嘗試添加約束(我使用的自動佈局),使表視圖的垂直邊界匹配的容器觀點:

UITableView *tableView = self.searchResultsSourcesTVC.tableView; 
NSDictionary *views = NSDictionaryOfVariableBindings(tableView); 

tableView.translatesAutoresizingMaskIntoConstraints = NO; // without this line there are conflicts 

[self.searchResultsContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[tableView]|" options:0 metrics:Nil views:views]]; 
[self.view layoutIfNeeded]; // not sure whether this line is necessary 

現在有沒有表都沒有。只是一個空白的觀點。

我在做什麼錯?什麼是以編程方式向容器視圖添加表視圖的最佳方式,並使表視圖的邊界與容器視圖的邊界一致?謝謝

+0

創建的左/右側的約束太多,然後看看會發生什麼...... – tarmes

回答

5

看起來你沒有足夠的限制來完全描述你需要的尺寸。例如,你似乎沒有水平限制。您通常需要4個約束才能充分表達要佈局的視圖的大小;具體而言,您需要中心X,中心Y,寬度和高度。

例如:

NSLayoutConstraint *con1 = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeCenterX relatedBy:0 toItem:view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]; 
NSLayoutConstraint *con2 = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeCenterY relatedBy:0 toItem:view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]; 
NSLayoutConstraint *con3 = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:0 toItem:view attribute:NSLayoutAttributeWidth multiplier:1 constant:0]; 
NSLayoutConstraint *con4 = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:0 toItem:view attribute:NSLayoutAttributeHeight multiplier:1 constant:0]; 
NSArray *constraints = @[con1, con2, con3, con4]; 
[self.searchResultsController addConstraints:constraints]; 
相關問題