-1

这是我的控制器的简化版本。我正在创建一个表视图,并使用一个核心数据查询来初始化这个控制器,该查询返回一个包含大约 300 个对象的数组。

我通过将每个单元格的高度硬编码为 100.0f 来简化这里的代码。不是只加载第一次加载时在屏幕上实际可见的前 5-6 个单元格,而是对 heightForRowAtIndexPath 的调用实际上完成了 300 次(对于所有单元格),这使得 UI 加载缓慢。

知道我在这里可能做错了什么吗?

@interface PortsViewController () <UITableViewDataSource, UITableViewDelegate>
    @property (nonatomic, strong) UITableView *tableView;

    @end

    @implementation PortsViewController

    #pragma mark - setters
    - (void)setPorts:(NSArray *)ports
    {
        _ports = ports;
    }

    #pragma mark - Controller Methods
    - (id)init
    {
        self = [super init];
        self.screenName = kPortsListPage;
        NSArray *ports = [Port MR_findAllSortedBy:@"name" ascending:TRUE];
        [self setPorts:ports];
        return self;
    }

    - (void)loadView {
        self.view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        [self loadTableView];
    }

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;

        self.title = @"Ports";
    }

    #pragma mark - Load Helpers
    -(void)loadTableView {
        self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

        [self.view addSubview:self.tableView];
    }

    #pragma mark - UITableViewDataSource Methods
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return [self.ports count];
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        PortTableViewCell* cell = [table dequeueReusableCellWithIdentifier:@"port"];

if (!cell) {
    PortTableViewCell* cell = [[PortTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"port"];
}

        cell.port = self.ports[indexPath.row]; 
        return cell;
    }

    #pragma mark - UITableViewDelegate Methods
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        NSLog(@"here");
        return 100.0f;
    }

    @end
4

1 回答 1

0

表格视图需要知道它的总高度。如果您实现heightForRowAtIndexPath:它将为每一行调用,以便表格知道它有多高。

如果每一行都具有相同的高度,只需rowHeight在 table view 上设置属性,而不是实现heightForRowAtIndexPath委托方法。

如果每一行都可以有不同的高度,那么除了使您的实施heightForRowAtIndexPath尽可能高效之外,您几乎无能为力。

estimatedRowHeight从 iOS 7 开始,属性现在位于UITableView. 使用它应该有助于改善事情。

于 2014-03-28T18:07:50.713 回答