Dizzle ,創建自定義單元格和使用控制在運行時以及來自Xib。
1)在Xib或Storyboard中的ViewController中創建CustomCell。
2)給出的標識符的小區![Give Identifier for your cell](https://i.stack.imgur.com/1HU5M.png)
3)的tableview你的cellForRowAtIndexPath數據源的方法添加以下代碼
static NSString *cellId = @"CustomIdenfier";
CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:firstCellId];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[self createCustomCell:cell atIndexPath:indexPath];
}
[self updateCustomCell:cell atIndexPath:indexPath];
return cell;
4)createCustomCell方法如果在XIB添加控制則不需要這種方法
-(void)createCustomCell:(CustomCell*)cell atIndexPath:(NSIndexPath*)indexPath{
//Here I am adding custom label run time, you can add
// Any control in Xib and create a reference IBOutlet for it and user here.
UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, cell.contentView.frame.size.width-10, 30)];
lblTitle.textColor = [UIColor blackColor];
lblTitle.tag = 1;
[cell.contentView addSubview:lblTitle];
}
5)updateCustomCell方法
-(void)updateCustomCell:(CustomCell*)cell atIndexPath:(NSIndexPath*)indexPath{
UILabel *lblTitle = (UILabel*)[cell.contentView viewWithTag:1];
[lblTitle setText:[NSString stringWithFormat:@"%i",indexPath.row]];
}
//編輯1 如果不使用Storyboard,則創建UITableviewCell的自定義擴展。
//CustomCell.h
#import <UIKit/UIKit.h>
@interface CustomCell : UITableViewCell
@property (strong, nonatomic) UILabel *lblTitle;
@end
//CustomCell.m
#import "CustomCell.h"
@implementation CustomCell
@synthesize lblTitle;
- (void)awakeFromNib {
NSLog(@"imgUrl:%@ txtName:%@",imgUser,txtName);
// Initialization code
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(nullable NSString *)reuseIdentifier{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if(self){
//Setup your Cell like initialising variables and setting frames of controls
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
我看到你的代碼有兩個明顯的問題:1)'dequeueReusableCellWithIdentifier:'可能返回null,所以你需要創建一個新的cell實例。你最好使用'dequeueReusableCellWithIdentifier:forIndexPath:',它根據需要自動分配單元格,2)在重用單元時,你一次又一次地添加'subjectField'子視圖。您應該在XIB中添加一次,或者檢查它是否已經添加到您的代碼中。 –