2013-04-24 68 views
0

我想在不创建自定义单元类的情况下创建自定义单元格。我知道这是可能的。我在storyboard中创建了一个带有标签的原型单元格的tableviewcontroller。在attibutes中,我设置了单元名称“mycell”。而我使用的代码是:CustomCell without storyCell class with storyboard

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ static NSString *CellIdentifier = @"mycell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) 
    { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];} 
    UILabel *title = (UILabel*) [cell viewWithTag:1]; 
    title.text = @"Hi"; 
    return cell; 
} 

但是,当我的应用程序来看,我看到的只是一个空表,而我的标签细胞。 (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {return 1;} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {return 5; }

谢谢。

+0

你看到5个部分? – iOSGuru248 2013-04-24 15:25:41

+0

我复制了你的代码,它对我来说工作得很好。您是否将控制器设置为表视图的数据源?你是否将IB中表视图控制器的类更改为这个类(你的发布代码在哪里)? – rdelmar 2013-04-24 15:39:02

+0

我正确设置了数据源和委托,并将故事板中表格视图控制器的类更改为此类。但是这段代码仍然不适合我。 – user2136333 2013-04-24 15:51:47

回答

0

如果以编程方式添加UILabel,它需要分配init,应给予一个框架并作为子视图添加到单元中。

UILabel *title = (UILabel*) [cell viewWithTag:1]; 
title.text = @"Hi"; 
return cell; 

应该

UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(50, 10, 50, 20)]; 
title.text = @"Hi"; 
[cell addSubview:title]; 
return cell; 

enter image description here

+0

谢谢,但如果我使用此代码,我在代码中分配一个标签,并且标签分配与故事板中的标签与标签1之间没有相关性。我在单元格内的故事板中创建了标签1,并且我想要使用它。 – user2136333 2013-04-24 15:35:20

+0

@ user2136333:你的意思是你已经有了标签1的XIB UILabel插座? – 2013-04-24 15:37:01

+1

@Deepesh,OP不需要插座,因为他通过在IB中设置的标签引用标签。 – rdelmar 2013-04-24 15:43:41