我将UITableViewCell子类化为自定义它,但我认为我错过了一些东西,因为:1)它不起作用2)有一些我很困惑的事情.除了自定义.xib文件的外观之外,我还更改了backgroundView,并且该部分工作正常.我最不理解/最困惑的部分是init方法,所以我在这里发布了.如果事实证明这是正确的,请告诉我,以便我可以发布可能是原因的更多代码.
这是我定制的init方法.我对“风格”的想法感到困惑,我想我只是用一个不同的backgroundView返回一个普通的UITableViewCell.我的意思是,那里没有任何东西引用.xib或做任何事情,只是从自己改变.backgroundView:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier wait: (float) wait fadeOut: (float) fadeOut fadeIn: (float) fadeIn playFor: (float) playFor { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { CueLoadingView* lview = [[CueLoadingView alloc] initWithFrame:CGRectMake(0,320,53)]; self.backgroundView = lview; [self setWait:wait]; // in turn edits the lview through the backgrounView pointer [self setFadeOut:fadeOut]; [self setFadeIn:fadeIn]; [self setPlayFor:playFor]; } return self; }
除了.xib和几个setter和getter之外,这是我的代码中唯一真正的部分,它与检索单元格有关.
附加信息:
1)这是我的.xib,它与班级相关联.
2)这是调用/创建UITableView(委托/视图控制器)的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *simpleTableIdentifier = @"CueTableCell"; CueTableCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; if (cell == nil) { cell = [[CueTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier wait:5.0 fadeOut:1.0 fadeIn:1.0 playFor:10.0]; [cell updateBarAt:15]; } return cell; }
解决方法
在nib文件中创建自定义表格视图单元格的最简单方法(自iOS 5.0起可用)是在表格视图控制器中使用registerNib:forCellReuseIdentifier :.最大的优点是dequeueReusableCellWithIdentifier:然后在必要时自动从nib文件中实例化一个单元格.你不再需要if(cell == nil)… part.
在您添加的表视图控制器的viewDidLoad中
[self.tableView registerNib:[UINib nibWithNibName:@"CueTableCell" bundle:nil] forCellReuseIdentifier:@"CueTableCell"];
你可以在cellForRowAtIndexPath中完成
CueTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CueTableCell"]; // setup cell return cell;
从nib文件加载的单元格使用initWithCoder进行实例化,如有必要,可以在子类中覆盖它.要修改UI元素,您应该覆盖awakeFromNib(不要忘记调用“super”).