如何使用故事板在自定义UIViewController中的UITableView中显示自定义UITableViewCell?

时间:2013-03-17 02:59:06

标签: ios objective-c uitableview uiviewcontroller

我认为我现在非常接近,但我遗漏了一些东西。如果我在tableView:cellForRowAtIndexPath方法中返回单元格之前中断,则单元格保存正确的数据。但它不会出现在table。我假设我的UITableView没有正确地连接到UIViewController。

这是我的自定义单元格:SCCustomerTableCell.h

#import <UIKit/UIKit.h>
#import "SCCustomer.h"

@interface SCCustomerTableCell : UITableViewCell

@property (strong, nonatomic) IBOutlet UILabel *companyLabel;
-(void)configureCellWithCustomer:(SCCustomer *)customer;

@end

SCCustomerTableCell.m

#import "SCCustomerTableCell.h"

@implementation SCCustomerTableCell

-(void)configureCellWithCustomer:(SCCustomer *)customer
{
    self.companyLabel = [[UILabel alloc] init];
    self.companyLabel.text = [customer dbaName];
}

@end

自定义视图控制器:SCCustomersVC.h

#import <UIKit/UIKit.h>
#import "SCCustomerTableCell.h"
#import "SCDataObject.h"

@interface SCCustomersVC : UIViewController <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>

@property (strong, nonatomic) IBOutlet UITableView *customersTable;
@property SCDataObject *dataObject;
@property (nonatomic, strong) NSArray *customers;

@end

SCCustomersVC.m

#import "SCCustomersVC.h"
#import "SCSplitVC.h"
#import "SCDataObject.h"

@interface SCCustomersVC ()
@end

@implementation SCCustomersVC

@synthesize customersTable;

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.customers count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CustomerCell";
    [self.customersTable registerClass:[SCCustomerTableCell class] forCellReuseIdentifier:CellIdentifier];
    SCCustomerTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    SCCustomer *customer = (SCCustomer *)[self.customers objectAtIndex:indexPath.row];
    [cell configureCellWithCustomer:customer];
    return cell;
}

编辑:我忘记了故事板连接的屏幕:
SCCustomersVCUITableViewSCCustomerTableCellUILabel

1 个答案:

答案 0 :(得分:1)

好的,有几件事你做错了。我从屏幕截图中看到,您没有将控制器设置为表视图的数据源或委托。你需要这样做。其次,如果在IB中的表视图中创建自定义单元格,则无需注册该类,只需确保已设置标识符。第三,既然您在IB中创建了标签,并且有一个插座,那么您不需要在单元格的.m文件中分配init - 事实上,您在.m中根本不需要任何东西。只需将cell.companyLabel.text = ...放在cellForRowAtIndexPath方法中。