我有一些自定义UITableViewCell的问题以及如何使用故事板管理事物.当我把样式代码放入initWithCoder:其中时不起作用,但如果我把它放入其中tableView: cellForRowAtIndexPath:就行了.在storyboard中我有一个原型单元格,其class属性设置为我的UITableViewCell自定义类.现在代码initWithCoder:被调用了.
SimoTableViewCell.m
@implementation SimoTableViewCell
@synthesize mainLabel, subLabel;
-(id) initWithCoder:(NSCoder *)aDecoder {
if ( !(self = [super initWithCoder:aDecoder]) ) return nil;
[self styleCellBackground];
//style the labels
[self.mainLabel styleMainLabel];
[self.subLabel styleSubLabel];
return self;
}
@end
Run Code Online (Sandbox Code Playgroud)
TableViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"NearbyLandmarksCell";
SimoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//sets the text of the labels
id<SimoListItem> item = (id<SimoListItem>) [self.places objectAtIndex:[indexPath row]];
cell.mainLabel.text = [item mainString];
cell.subLabel.text = [item subString];
//move the labels so that they are centered horizontally
float mainXPos = (CGRectGetWidth(cell.contentView.frame)/2 - CGRectGetWidth(cell.mainLabel.frame)/2);
float subXPos = (CGRectGetWidth(cell.contentView.frame)/2 - CGRectGetWidth(cell.subLabel.frame)/2);
CGRect mainFrame = cell.mainLabel.frame;
mainFrame.origin.x = mainXPos;
cell.mainLabel.frame = mainFrame;
CGRect subFrame = cell.subLabel.frame;
subFrame.origin.x = subXPos;
cell.subLabel.frame = subFrame;
return cell;
}
Run Code Online (Sandbox Code Playgroud)
我已经调试了代码并发现dequeue...首先调用它,然后它进入initWithCoder:然后返回到视图控制器代码.奇怪的是,内存中的单元格地址在return self;返回控制器之间和之间发生变化.如果我在dequeue...一切正常后将样式代码移回视图控制器.只是我不想在重复使用单元格时做不必要的样式.
干杯
Wai*_*ain 13
在initWithCoder:单元格上调用之后,将创建单元格并设置其属性.但是,单元格上的XIB(IBOutlets)中的关系尚未完成.因此,当您尝试使用时mainLabel,它是一个nil参考.
将样式代码移动到awakeFromNib方法中.在解压缩XIB之后,在创建单元并完全配置单元后调用此方法.
| 归档时间: |
|
| 查看次数: |
2777 次 |
| 最近记录: |