Reputation: 17461
I'm working with a Today Extension, displaying a UITableView
. There are only a couple of items, but I get empty rows as well.
I'm able to use Auto Layout with an outlet constrain on the table view height to resize the table to fit only the rows with content.
What I'm not able to do is make the widget resize to wrap the table view. At the moment I'm left with a properly sized table and a lot of empty space.
Upvotes: 9
Views: 7163
Reputation: 961
If you want the widget's controller to be the height of the tableView, do this:
self.preferredContentSize = self.tableView.contentSize;
You should set this each time you reload your data of the tableView and the height would change. You don't have to worry about the contentSize's width because the system ignores it.
To correct your answer above, you would need to add:
self.view.translatesAutoresizingMaskIntoConstraints = NO;
That should fix the constraint warnings.
Upvotes: 16
Reputation: 17461
I've found a solution, it compiles and render as wanted, but triggers a warning.
Simply have the table view sticking to the view controller's view edges.
In viewWillAppear
we can set the height of the view controller's view to be the same as the table view contentSize
.
NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:self.view
attribute:NSLayoutAttributeHeight
relatedBy:0
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1
constant:self.tableView.contentSize.height];
heightConstraint.priority = UILayoutPriorityRequired;
[self.view addConstraint:heightConstraint];
[self.view needsUpdateConstraints];
[self.view setNeedsLayout];
The code above works fine, and also solves having to add the outlet constraint on the table view height, but generates this warning:
Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSLayoutConstraint:0x7af81290 'UIView-Encapsulated-Layout-Height' V:[UIView:0x7af7f560(171)]>",
"<NSLayoutConstraint:0x7e1c1010 V:[UIView:0x7af7f560(132)]>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7af81290 'UIView-Encapsulated-Layout-Height' V:[UIView:0x7af7f560(171)]>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
Upvotes: 0