使用带有标签的标签可以完成工作,但从来都不是一个好的做法……最好的方法是创建一个自定义的 UITableViewCell 类。
即选择
新建文件>Cocoa Touch >Objective C 类
和
将其创建为 UITableViewCell 的子类
现在您将获得 .h 和 .m 文件..
下一步是为此创建单元格的视图
选择
新建文件>用户界面>空
现在使用与您的 customcell 类相同的名称创建它(比如说“CustomCell”)
现在您将拥有三个文件 CustomCell.h,CustomCell.m,CustomCell.xib
现在选择 xib 文件并在 xib 上添加 UITableViewCell 对象并将其自定义类设置为“CustomCell”
看下图
在此之后,您可以将任何东西(UIImageView、UITextfield、UIButton)拖到下面的视图中,并在 CustomClass 上提供出口并使用委托方法管理操作..
如果您有 imageView 出口作为 titleImage ..那么您可以通过在 CellForRowAtIndex (TableView 德尔门方法)中创建单元格对象来设置图像。
cell.titleImage=[UIImage ImageNamed:@"goo.png"];
现在我要说的还有一件事是你必须在 CustomCell.m 中实现一个 init 方法来加载笔尖>>
它看起来像下面的代码。
-(id)initWithDelegate:(id)parent reuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [self initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier])
{
self=(CustomCell*)[[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:nil options:nil] lastObject];
}
self.backgroundColor = [UIColor clearColor];
self.backgroundView = NULL;
self.selectedBackgroundView =NULL;
//If you want any delegate methods and if cell have delegate protocol defined
self.delegate=parent;
//return cell
return self;
}
如果您在单元格上使用按钮,现在最好有代表
以便在按钮操作方法中调用委托方法(传递单元对象)并在 ViewController 中使用 TableView 实现委托
这里是例子
现在您可以使用您的单元格为 UITableView 填充...并且不要在 CustomCell.xib 中设置重用标识符值(与设置 CustomClass 相同)
让我们设置它,嗯还有什么“customCell”
所以在填充 tableView 时使用
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier=@"customCell";
CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell==nil)
cell= [[CustomCell alloc] initWithDelegate:self reuseIdentifier:cellIdentifier];
//set cell properties
cell.titleImage=[UIImage ImageNamed:@"title.png"];
return cell;
}
别忘了添加委托方法
给
ViewController:UIViewController<CustomCellDelegate>
在 ViewController 的 ViewController.h 文件中
然后在你的 ViewController.m 中实现它的主体(实现文件)
作为
-(void)cellButtonPressed:(CustomCell*)cell
{
NSIndexPath *indexPathOfPressedCell = [self.tableView indexPathForCell:cell];
NSLog(@"Pressed");
}
这看起来像是一个很长的方法,但它非常有用且可读...
-------NB----------:
另外,返回 CustomCell 高度
通过实施
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{}
它可能会发生......