[英]How to use Custom Static UITableViewCells to display images in cell?
我有一個包含5個靜態單元格的tableview。 它們是靜態的,因為在表視圖中總是只有5個。
我想要它們自定義單元格,因為我需要在每個單元格中居中UIImageViews,因為它們將具有按鈕圖像,而沒有其他內容。 我使用UIImageView插座創建了MyCustomCell類,並將其連接到插座。
然后在tableview控制器類中這樣做:
#pragma mark - TableView Cell Methods
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCustomCell *cell = [[MyCustomCell alloc] init];
switch (indexPath.row) {
case 0:
// Use Custom Cell
cell.thumbnailImageView.image = [UIImage imageNamed:@"button.png"];
break;
case 1:
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
// USE IMAGE INSTEAD
cell.thumbnailImageView.image = [UIImage imageNamed:@"button1.png"];
break;
case 2:
cell.thumbnailImageView.image = [UIImage imageNamed:@"button2.png"];
break;
case 3:
cell.thumbnailImageView.image = [UIImage imageNamed:@"button3.png"];
break;
case 4:
cell.thumbnailImageView.image = [UIImage imageNamed:@"Search.png"];
break;
default:
break;
}
return cell;
}
MyCustomCell.m:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
單元格顯示為空白。 當我使用UITableViewCell代替MyCustomCell時,它工作正常。 所以我不確定為什么現在失敗了。
我在MyCustomCell.m
中看不到引用自定義單元的.xib文件的任何地方。 您必須告訴類要加載哪個.xib文件。
請查看以下教程,該教程演示了一種從.xib文件加載單元的方法(在自定義單元類中): 從XIB創建自定義UITableViewCell –分步教程
這個問題顯示了另一個方法(在cellForRowAtIndexPath
內): 如何從xib創建自定義tableViewCell
另外,如果要在cellForRowAtIndexPath
重新創建靜態單元格,則不會真正使用它們。 您將丟失在Interface Builder中設置的所有內容。 考慮放棄靜態單元格。 您可以只在設置圖像的同一位置設置所有單元格屬性。
最后,如果您放棄使用靜態單元格方法,請考慮在與表視圖相同的視圖控制器中創建自定義單元格(標准UITableView
為此具有一個占位符單元格),並以標准方式將自定義單元格出隊。 然后,沒有其他要加載的.xib,因此它將自動處理。 請參閱我先前的答案,以獲取有關創建像這樣的自定義表格視圖單元格的更多詳細信息。
如果您使用的是靜態單元格,則只需為每個單元格創建IBOutlet,然后執行以下操作:
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCustomCell *cell = nil;
switch (indexPath.row) {
case 0:
cell0.thumbnailImageView.image = [UIImage imageNamed:@"button.png"];
cell = cell0;
break;
case 1:
//you can set the accessory type in the storyboard
[cell1 setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
cell1.thumbnailImageView.image = [UIImage imageNamed:@"button1.png"];
cell = cell1;
break;
//etc
}
return cell;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.