目标C:如何通过代码创建自定义/静态表视图单元格

Zhe*_*hen 4 objective-c uitableview ios

我正在尝试使用代码(w/o nib)创建3个表格视图单元格.我在使代码工作时遇到了一些麻烦.我想我的方法不对.任何人都可以告诉我正确的方法吗?任何有关这方面的帮助将不胜感激!

谢谢!

真鹤

我的代码片段如下:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section     
{
    // Return the number of rows in the section.
    return 3;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *CellIdentifier = @"Cell";
    int row = [indexPath row];

    UITableViewCell *startCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    UITableViewCell *durationCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    UITableViewCell *radiusCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

    startCell.textLabel.text = @"Start:";
    durationCell.textLabel.text = @"Duration:";
    radiusCell.textLabel.text = @"radius";


    if (row == 0)
    {
        return startCell;
    }
    else if (row == 1)
    {
        return durationCell;
    }

    return radiusCell;
}
Run Code Online (Sandbox Code Playgroud)

编辑(19/05/11)

在完成您的答案后,我仍然无法在我的tableview中显示任何单元格.这是由于我初始化表格的方式吗?

//Initialization
UITableView *tv = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.settingsView.frame.size.height)
                                                style:UITableViewStyleGrouped];

self.tableView = tv;

[self.view addSubview:tableView];
Run Code Online (Sandbox Code Playgroud)

之后我有一个动画来扩展tableView

[UIView animateWithDuration:0.3 animations:^{

        [self.tableView setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-self.picker.frame.size.height)];
}];
Run Code Online (Sandbox Code Playgroud)

你们看到上述任何问题吗?导致我显示细胞的任何事情都会失败?

谢谢!

oct*_*cty 6

UITableView初始化代码中,我看不到您在何处设置表视图delegatedataSource.这肯定是问题的一部分.根据Apple的文档:

UITableView对象必须具有充当数据源的对象和充当委托的对象; 通常,这些对象是应用程序委托,或者更常见的是自定义UITableViewController对象.数据源必须采用UITableViewDataSource协议,委托必须采用UITableViewDelegate协议.数据源提供UITableView在插入,删除或重新排序表的行时构造表和管理数据模型所需的信息.委托提供表使用的单元格并执行其他任务,例如管理附件视图和选择.

这是你可以尝试做的:

//Initialization
UITableView *tv = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.settingsView.frame.size.height)
                                                style:UITableViewStyleGrouped];

// assuming that your controller adopts the UITableViewDelegate and
// UITableViewDataSource protocols, add the following 2 lines:

tv.delegate = self;
tv.dataSource = self;


self.tableView = tv;

[self.view addSubview:tableView];
Run Code Online (Sandbox Code Playgroud)