Ios 使用故事板和子类的自定义UITableViewCell
我创建了Ios 使用故事板和子类的自定义UITableViewCell,ios,uitableview,storyboard,subclass,Ios,Uitableview,Storyboard,Subclass,我创建了UITableViewCell的子类,并将其命名为DCCustomCell。这是DCCustomCell.h文件 #import <UIKit/UIKit.h> @interface DCCustomCell : UITableViewCell @property (weak, nonatomic) IBOutlet UIImageView *imageView; @property (weak, nonatomic) IBOutlet UILabel *title; @
UITableViewCell
的子类,并将其命名为DCCustomCell
。这是DCCustomCell.h
文件
#import <UIKit/UIKit.h>
@interface DCCustomCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *title;
@property (weak, nonatomic) IBOutlet UILabel *date;
@property (weak, nonatomic) IBOutlet UILabel *price;
@end
这是tableView:cellForRowAtIndexPath:method:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"CustomCell";
DCCustomCell *cell = (DCCustomCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
NSLog(@"%@" ,cell);
cell.imageView.image = [UIImage imageNamed:@"info_button.png"];
cell.title.text = @"Hello!";
cell.date.text = @"21/12/2013";
cell.price.text = @"€15.00";
return cell;
}
问题是imageView设置正确,但所有标签都是空白的。如果将imageView属性名称更改为例如eventImageView,则不会设置图像。
结果是:
我想不出怎样才能解决这个问题
编辑:如果我删除
[self.tableView registerClass:[DCCustomCell class] forCellReuseIdentifier:@"CustomCell"];
从viewDidLoad
中,所有操作似乎都正常。为什么?试试:
if (cell == null) {
//create and initialize cell
}
之后
DCCustomCell *cell = (DCCustomCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
首先正确检查插座,确保所有标签均已连接,并写下以下内容:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"CustomCell";
DCCustomCell *cell = (DCCustomCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DCCustomCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSLog(@"%@" ,cell);
cell.imageView.image = [UIImage imageNamed:@"info_button.png"];
cell.title.text = @"Hello!";
cell.date.text = @"21/12/2013";
cell.price.text = @"€15.00";
return cell;
}
您是否已将控件绑定到IBOutlet? 您可以尝试直接在情节提要中将DCCustomCell设置为UITableviewCell的类。
然后,您需要在单元格中设置带有控件的插座,因为您注意到它在删除时起作用
[self.tableView registerClass:[DCCustomCell class] forCellReuseIdentifier:@"CustomCell"];
只有在使用dequeueReusableCellWithIdentifier:indexPath:
并且尚未在标识检查器中为该单元格设置自定义类时,才需要执行此操作。如果使用registerClass:forCellReuseIdentifier
则单元格将使用initWithStyle:reuseIdentifier:
而不是initWithCoder:
进行初始化,从而破坏您在故事板中建立的连接
[self.tableView registerClass:[DCCustomCell class] forCellReuseIdentifier:@"CustomCell"];