自定义表格视图单元格是解决此问题的最佳方法,这里我们需要创建不同的自定义表格视图单元格控制器并在 cellForAtIndexPath 表格视图数据源中使用它:
CustomTableViewCell.h
#import <UIKit/UIKit.h>
@interface CustomTableViewCell : UITableViewCell
@property (nonatomic, readonly) UILabel *tblViewLabel;
@property (nonatomic, readonly) UIButton *tblViewBtn;
@end
CustomTableViewCell.m
#import "CustomTableViewCell.h"
@implementation CustomTableViewCell
@synthesize tblViewLabel = _tblViewLabel;
@synthesize tblViewBtn = _tblViewBtn;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString
*)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
_tblViewLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 8, 50, 30)];
[self.contentView addSubview:_tblViewLabel];
[_tblViewLabel release];
_tblViewBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
_tblViewBtn.frame = CGRectMake(100, 5, 200, 20);
[_tblViewBtn.titleLabel setText:[NSString stringWithFormat:@"%d",self.tag]];
[_tblViewBtn addTarget:self action:@selector(tblBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.contentView addSubview:_tblViewBtn];
[_tblViewBtn release];
}
return self;
}
- (void)tblBtnPressed :(UIButton *)btn {
NSLog(@"Here %d button is pressed.",btn.tag);
}
- (void)dealloc {
[_tblViewLabel release];
[_tblViewBtn release];
[super dealloc];
}
@end
//------------------------------------//
Here In Your Previous controller's cellForRowAtIndexPath datasource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *MyIdentifier = @"MyIdentifier";
CustomTableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:MyIdentifier] ;
if (cell == nil){
cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier];
}
cell.tblViewLabel.text =[NSString stringWithFormat:@"%d",indexPath.row];
[cell.tblViewBtn setTitle:[NSString stringWithFormat:@"%d",indexPath.row] forState:UIControlStateNormal];
cell.tblViewBtn.tag = indexPath.row;
return cell;
}