I am using autolayout in Xcode 5.
I set the table view\'s height to Greater than or equal to 200px. I want that it has dynamic size. Because sometimes it will have many
This is tested with the latest version of Xcode.
1) In Xcode go to the storyboard and click on you table view to select it.
2) In the Utilities pane (see picture 1) make sure the constraint for the table view height is defined.
3) In the view controller that displays the table view create an outlet to this constraint:
In Swift 3
@IBOutlet weak var dynamicTVHeight: NSLayoutConstraint!
In Objective C
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *dynamicTVHeight;
4) In the storyboard go back to the height constraint for the UITableView
and verify that the icon in the right has changed the color from purple to blue (see picture 2)
4) Also put this code in the same view controller:
Swift
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let height = min(self.view.bounds.size.height, tableView.contentSize.height)
dynamicTVHeight.constant = height
self.view.layoutIfNeeded()
}
Objective C
- (void)viewWillAppear:(BOOL)animated
{
// just add this line to the end of this method or create it if it does not exist
[self.tableView reloadData];
}
-(void)viewDidLayoutSubviews
{
CGFloat height = MIN(self.view.bounds.size.height, self.tableView.contentSize.height);
self.dynamicTVHeight.constant = height;
[self.view layoutIfNeeded];
}
This should solve your problem.
These are the links to two versions of the sample project that does what you want, one for Objective C and the other one for Swift 3. Download it and test it with Xcode. Both projects work with the latest version of Xcode, Xcode 8.3.2.
https://github.com/jcatalan007/TestTableviewAutolayout https://github.com/jcatalan007/TestTableviewAutolayoutSwift