Tom*_*aid 36 storyboard uitableview ios ios5
我正在转换到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;
}
Run Code Online (Sandbox Code Playgroud)
我已经看到了删除"if(cell == nil)"块的示例.但是,如果我把它拿出来,我的应用程序会崩溃并显示以下消息:"UITableView dataSource必须从tableView返回一个单元格:cellForRowAtIndexPath:".这不是问题,因为它的工作原理如上所示.
我的问题是我想为单元格使用自定义样式,因此不能使用initWithStyle.如何初始化我在故事板上设计的自定义单元格?
旧的5前应用程序有一个笔尖和类使用这样的东西,但现在我正在使用故事板.
- (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;
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*lex 39
这条路
- (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;
}
Run Code Online (Sandbox Code Playgroud)
小智 9
这对我来说很完美(Xcode 4.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;
}
Run Code Online (Sandbox Code Playgroud)
重要提示:不要忘记设置委托和数据源.
如果使用以下方法加载包含tableview的视图控制器:
MyViewController *myViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];
Run Code Online (Sandbox Code Playgroud)
然后cellForRowAtIndexPath你只需要一行:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifierFromStoryboard"];
Run Code Online (Sandbox Code Playgroud)
dequeueReusableCellWithIdentifier 如果不存在,将实例化一个单元格.
| 归档时间: |
|
| 查看次数: |
54229 次 |
| 最近记录: |