【发布时间】:2016-03-15 01:15:21
【问题描述】:
所以我有一个自定义的 UITableViewCell:
TestTableViewCell.h
#import <UIKit/UIKit.h>
@interface TestTableViewCell : UITableViewCell
@property (strong, nonatomic) IBOutlet UILabel *testCellLabel;
@end
TestTabelViewCell.m
#import "TestTableViewCell.h"
@implementation TestTableViewCell
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
_testCellLabel = [[UILabel alloc] init];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
然后我有一个带有使用自定义表格视图单元格的表格视图的视图控制器。但是这个问题是我不想在 cellForRowAtIndexPath 中使用 dequeueReusableCellWithIdentifier。相反,我想要一个单元格数组。
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
@end
ViewController.m
#import "ViewController.h"
#import "TestTableViewCell.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSArray *myTableViewCells;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSArray *)myTableViewCells {
TestTableViewCell *cell1 = [[TestTableViewCell alloc] init];
cell1.testCellLabel.text = @"one";
cell1.backgroundColor = [UIColor blueColor];
TestTableViewCell *cell2 = [[TestTableViewCell alloc] init];
cell2.testCellLabel.text = @"two";
cell1.backgroundColor = [UIColor greenColor];
if (!_myTableViewCells) {
_myTableViewCells = @[cell1, cell2];
}
return _myTableViewCells;
}
#pragma mark - UITableView delegate functions
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.myTableViewCells.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TestTableViewCell *cell = self.myTableViewCells[indexPath.row];
return cell;
}
@end
问题是表格视图单元格中没有出现testCellLabel。我知道细胞在那里,因为我设置了它们的背景颜色。
与几个人交谈后,显然我需要从 XIB 或 NIB 进行某种加载,以便 UI 正确加载?即使标签是在情节提要的单元格中定义的。
我知道这违反了规范,Apple 确实希望您使用 dequeueReusableCellWithIdentifier,但我知道它在我需要它的情况下不起作用。我已经阅读了这么多 请不要只是告诉我使用它。这个代码示例只是非常基本的,例如起见和易用性。
任何帮助将不胜感激。
【问题讨论】:
-
你在哪里调用这个 myTableViewCells 方法?
-
我会告诉你只使用
dequeueReusableCellWithIdentifier:。我怀疑你有一个不起作用的场景。您将遇到 UITableView 的问题,抱怨您没有从dequeueReusableCellWithIdentifier:获取单元格。 -
为什么不能使用
dequeueReusableCellWithIdentifier?我简直不敢相信 ==! -
@Mr.T myTableViewCells 方法是自定义设置器
标签: ios objective-c uitableview