我正在创建一个我想在 iOS7 和 iOS8 下运行的应用程序,它具有可变的表格单元格高度。在 iOS7 中,我曾经定义一个原型单元格,然后在 heightForRowAtIndexPath 中使用它来计算高度,基于放置在标签中的文本的大小。
使用 Xcode 6 时,这似乎不再起作用。我今天创建了一个小型测试应用程序,看看我是否疯了(也许我疯了)。我从根本不定义 heightForRowAtIndexPath 开始。当我用 iOS7 和 iOS8 设备测试它时,它的行为不同。在 iOS8 设备中,它会自动确定单元格高度并且工作正常。在 iOS7 中,所有单元格都返回相同的高度。它不会对带有可变文本的单元格进行自动高度调整,对于 iOS7,仅适用于 iOS8。
所以......我在想......嗯......在iOS8下我可以使用自动布局来确定高度,并且只为iOS7实现heightForRowAtIndexPath......
好的,所以...我尝试添加 heightForRowAtIndexPath。在 iOS7 下,它在方法 systemLayoutSizeFittingSize 上崩溃。我玩了几个小时,但我似乎没有做任何改变。这是非常简单的代码。
这是 UITableViewController 代码:
//
// TestTableViewController.m
// testTables
//
#import "TestTableViewController.h"
#import "Cell1.h"
@interface TestTableViewController ()
@property (nonatomic, strong) Cell1 *cellPrototype;
@end
@implementation TestTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerNib:[UINib nibWithNibName:@"Cell1" bundle:nil] forCellReuseIdentifier:@"Cell1"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
self.cellPrototype = [self.tableView dequeueReusableCellWithIdentifier:@"Cell1"];
self.cellPrototype.label1.text = [self cellContents:indexPath];
[self.cellPrototype layoutIfNeeded];
CGSize size = [self.cellPrototype systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Cell1 *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell1" forIndexPath:indexPath];
cell.label1.text = [self cellContents:indexPath];
return cell;
}
- (NSString*)cellContents:(NSIndexPath *)indexPath {
if (indexPath.row == 0) {
return @"one line";
}
else if (indexPath.row == 1) {
return @"two lines I think will result from this piece of text that goes over";
}
else if (indexPath.row == 2) {
return @"three lines I think will result from this piece of text that goes over and then even extends a little more again";
}
else {
return @"three lines I think will result from this piece of text that goes over and then even extends a little more again, and then extends over more and more lines like it will go on forever and never end but in fact it does end right here.";
}
}
@end
这是单元格标题(.m 文件中没有任何内容):
//
// Cell1.h
// testTables
//
#import <UIKit/UIKit.h>
@interface Cell1 : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *label1;
@end
这是单元格的xib。如您所见,它并不复杂:
那么......这种旧方法不再起作用了吗?如何获得将在两个 iOS 中运行的可变高度单元?