Reputation: 130092
I am currently porting an iOS application to autolayout and I found a problem I am unable to solve. The problem is a UITableView
.
The table is pretty simple:
Points 1. and 2. are simple but I don't know how to create a constraint that will force the views in different cells to have the same sizes.
Is there any autolayout solution for it or do I have to set the frames manually?
Upvotes: 4
Views: 1610
Reputation: 104082
I would do this by creating a custom cell class with the two labels. Give the left label a width constraint (as well as constraints to the left edge of the cell and centerY) and give the right label a horizontal spacing constraint to the left label. Make IBOutlets to the two labels, and also one to the left label's width constraint (I call it widthCon in my example). In my example I gave both labels a background color so I could see the widths. I calculate the width of the longest string in viewDidLoad, and then use that number to adjust the constant of the width constraint in cellForRowAtIndexPath:
@interface TableController ()
@property (strong,nonatomic) NSArray *theData;
@property (nonatomic) CGFloat maxWidth;
@end
@implementation TableController
- (void)viewDidLoad {
[super viewDidLoad];
self.theData = @[@"One",@"Two",@"Three Hundred Forty",@"Four",@"Five",@"Six",@"Seven",@"Eight",@"Nine"];
self.maxWidth = 0;
for (NSString *s in self.theData) {
CGSize stringSize = [s sizeWithFont:[UIFont systemFontOfSize:17]];
if (stringSize.width > self.maxWidth) self.maxWidth = stringSize.width;
}
[self.tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.theData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
RDCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
cell.widthCon.constant = self.maxWidth;
cell.leftLabel.text = self.theData[indexPath.row];
return cell;
}
Upvotes: 2