【问题标题】:Connecting UITableView Cells to separate View Controllers [closed]将 UITableView 单元连接到单独的视图控制器 [关闭]
【发布时间】:2013-01-04 17:27:32
【问题描述】:

我有多个单独的视图控制器(我需要),并希望将 TableView 中的每一行连接到单独的视图控制器。

至于代码,这是我目前所拥有的。我只做了tableView:

我的 ViewController.h

[...]
@interface SimpleTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
[...]

我的ViewController.m

[...]
@implementation SimpleTableViewController
{
NSArray *tableData;
}

[...]

- (void)viewDidLoad
{
[super viewDidLoad];
tableData = [NSArray arrayWithObjects:@"One", @"Two", @"Three", nil];
}

[...]

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [tableData count];
}

[...]

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
static NSString *simpleTableIdentifier = @"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}

cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
return cell;
}

我还将 tableView 连接到 dataSource 和委托。我需要的是让上面的每一个条目(一、二、三)连接到单独的视图控制器。我已经制作了所有的视图控制器。

【问题讨论】:

    标签: objective-c xcode uitableview tableview


    【解决方案1】:

    如果我正确理解您的问题,您只需要在 didSelectRowAtIndexPath 方法中使用 if-else 或 switch 语句:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        if (indexPath.row == 0) {
            ViewController1 *vc1 = "instantiate a controller here"
            [self.navigationController pushViewController:vc1 animated:YES];
        else if (indexPath.row == 1) {
            ViewController2 *vc2 = "instantiate a controller here"
            [self.navigationController pushViewController:vc2 animated:YES];
        etc......
    

    【讨论】:

      【解决方案2】:

      表格视图控制器中的每一行都是一个 UITableViewCell,所以我猜这就是您想要控制每一行的“视图控制器”时所指的内容。

      你需要继承 UITableViewCell 的子类,然后你可以在使用单元格时创建该子类的新实例

      - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
      

      编辑:当然,您不必继承 UITableViewCell,但如果您想完全控制它,那么您可以这样做。

      【讨论】:

        猜你喜欢
        • 2017-06-29
        • 2012-09-07
        • 1970-01-01
        • 1970-01-01
        • 2013-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多