我正在转换到iOS 5和故事板。当我有一个默认单元格样式的表视图时,一切都很正常。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifierFromStoryboard"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyIdentifierFromStoryboard"];
}
return cell;
}我见过删除"if (cell == nil)“块的例子。但是,如果我取出它,我的应用程序崩溃并显示消息:"UITableView dataSource必须从tableView:cellForRowAtIndexPath中返回一个单元格:“。这不是问题,因为它的工作方式如上图所示。
我的问题是,我希望对单元格使用自定义样式,因此不能使用initWithStyle。如何初始化我在故事板上设计的自定义单元格?
旧的pre-5应用程序有一个nib和class,使用了类似这样的东西,但现在我使用的是故事板。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCustomTableCell *cell = (MyCustomTableCell *) [tableView dequeueReusableCellWithIdentifier:@"MyCustomIdentifier"];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyCustomTableCell" owner:self options:nil];
cell = (MyCustomTableCell *) [nib objectAtIndex:0];
}
return cell;
}发布于 2012-02-18 03:32:40
这边请
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
return cell;
}发布于 2013-01-24 01:57:47
这非常适合我(Xcode4.5.2和iOS 6.0):
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if( cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
UILabel *title = (UILabel*) [cell viewWithTag:1000];
UILabel *summary = (UILabel*) [cell viewWithTag:1001];
[title setText:[ tableMainTitle objectAtIndex:indexPath.row]];
[summary setText:[ tableSubTitle objectAtIndex:indexPath.row]];
return cell;
}重要提示:不要忘记设置委托和数据源。
发布于 2012-08-09 18:09:43
如果您使用以下命令加载包含tableview的视图控制器:
MyViewController *myViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];然后在cellForRowAtIndexPath中,你只需要一行:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifierFromStoryboard"];如果不存在单元格,dequeueReusableCellWithIdentifier将实例化一个单元格。
https://stackoverflow.com/questions/9334156
复制相似问题