以前,当我使用storyboard创建UITableView时,我在属性检查器中设置单元格标识符并将其粘贴到方法cellForRowAtIndexPath
中,然后使用方法dequeueReusableCellWithIdentifier
创建新的UITableViewCell。但是,当我以编程方式创建UITableView时,我无处可设置单元标识符。我的意思是,我可以任意指定一个标识符,而不必在属性检查器中匹配。我对吗?在这种情况下我该如何创建UITableViewCell?
答案 0 :(得分:0)
您可以通过编程方式创建UITableview和UITableviewCell,如下所示。
以编程方式创建Tableview,
@interface ViewController () <UITableViewDataSource>{
//create tableview instance
UITableView *tableViewPro;
}
在viewDidLoad中分配
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// init table view
tableViewPro = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
// must set delegate & dataSource, otherwise the the table will be empty and not responsive
tableViewPro.dataSource = self;
tableViewPro.backgroundColor = [UIColor cyanColor];
// add to canvas
[self.view addSubview:tableViewPro];
}
在Tableview数据源方法中指定行数和UITableview单元格
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = @"Tableviewcell";
// Similar to UITableViewCell, but
TableViewCell *cell = (TableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
//initialize uitableviewcell programmatically.
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
// Just want to test, so I hardcode the data
cell.descriptionLabel.text = [NSString stringWithFormat:@"Testing index %ld",(long)indexPath.row];
return cell;
}
现在,以编程方式创建您的UITableviewCell。首先添加New-&gt; file-&gt; Cocoa Touch类 - &gt;输入带有UITableviewCell子类的tableviewcellname,并UNCHECK&#39;还创建XIB文件&#39;,因为将以编程方式创建单元格。
将创建两个文件.h和.m的UITableviewCell,我用TableViewCell名称创建UITableviewCell。下面是以编程方式实现它的代码。
@interface TableViewCell : UITableViewCell
@property (nonatomic,retain) UILabel *descriptionLabel;
@end
在TableViewCell的@implementation文件中合成descriptionLabel
@synthesize descriptionLabel = _descriptionLabel;
下面是以编程方式创建UITableviewCell的初始化函数函数。在TableViewCell的@implementation文件中添加这个功能
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
//it will create UITableiviewCell programmatically and assign that instance on self.
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// configure control(s)
self.descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 10, 300, 30)];
self.descriptionLabel.textColor = [UIColor blackColor];
self.descriptionLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];
[self addSubview:self.descriptionLabel];
}
return self;
}