我正在尝试以编程方式创建UITableView
,但这让我感到困惑,因为UITableViewDataSource
的协议实现的方法永远不会被调用
的ViewController
@interface viewController : UIViewController <UITableViewDataSource>
@end
#import "viewController.h"
@interface viewController ()
@property (strong, nonatomic) NSArray *tweetsArray;
@end
@implementation viewController {
UITableView *tableView;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.tweetsArray = [[NSArray alloc] initWithObjects:
@"This is the first line",
@"This is the second line",
@"This is the third line",
@"This is the fourth line",
@"This is the fifth line",
nil];
tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
tableView.dataSource = self;
[self.view addSubview:tableView];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.tweetsArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"SettingsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
NSString *tweet = [self.tweetsArray objectAtIndex:indexPath.row];
[cell.textLabel setText:@"Via Cuong Doan"];
[cell.detailTextLabel setText:tweet];
return cell;
}
@end
的AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
viewController *view = [[viewController alloc] init];
[self.window addSubview:view.view];
return YES;
}
一切似乎都很好,但-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
和-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
永远不会被称为
答案 0 :(得分:2)
你需要在didFinishLaunchingWithOptions中创建窗口,而且你不应该手动将控制器的视图添加到窗口,你应该让控制器成为窗口的根视图控制器,
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
ViewController *view = [[ViewController alloc] init];
self.window.rootViewController = view;
[self.window makeKeyAndVisible];
return YES;
}
答案 1 :(得分:0)
你有没有尝试过:
@interface viewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
在你的第一行?
答案 2 :(得分:0)
添加以下内容:
tableView.delegate = self;