如何在 Xcode 4.2 中以编程方式创建 UITableView 并填充 NSArray?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8720561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 22:53:39  来源:igfitidea点击:

How to Programmatically Create UITableView and Populate with NSArray in Xcode 4.2?

objective-cxcodeios5xcode4.2storyboard

提问by Jake

I have been struggling to understand the difference between Storyboards and coding in Objective-C. It appears you can create a UITableView by both dragging the object into your Storyboard, or coding in a new view within Objective-C.

我一直在努力理解 Storyboards 和 Objective-C 编码之间的区别。看起来您可以通过将对象拖到 Storyboard 中或在 Objective-C 中的新视图中编码来创建 UITableView。

The problem is that I want to keep my Storyboard as slim as possible. So I'm trying to build and populate a UITableView with an NSArray of 5 strings. My code will only run 1 row before returning a compiler error... I am going to scrap the whole project and start fresh.

问题是我想让我的 Storyboard 尽可能的纤薄。因此,我正在尝试使用包含 5 个字符串的 NSArray 构建和填充 UITableView。我的代码在返回编译器错误之前只会运行 1 行......我将废弃整个项目并重新开始。

I would be very grateful if somebody familiar with the new Xcode 4.2/iOS5/Storyboards can provide a reasonable solution for building the UITableView. I know this is such a basic task which is why it's so frustrating to begin with. I can get the Table View working, but I cannot seem to get an Array to dynamically fill and create #X number of rows...

如果熟悉新的 Xcode 4.2/iOS5/Storyboards 的人可以提供构建 UITableView 的合理解决方案,我将不胜感激。我知道这是一项如此基本的任务,这就是为什么开始时如此令人沮丧。我可以让表格视图工作,但我似乎无法获得一个数组来动态填充和创建#X 行数...

Let me know if I can provide any more info. I've tried to be as straightforward as possible - just need to get a TableView working and populate with an Array :)

如果我能提供更多信息,请告诉我。我试图尽可能简单 - 只需要让 TableView 工作并用数组填充:)

EDIT- here is my project source codeyou can download to check out where I'm at.

编辑- 这是我的项目源代码,您可以下载以查看我所在的位置。

回答by bryanmac

Here's a trivial sample with subclassing UITableViewController populated with an NSArray (NSMutableArray) from my sample code. It doesn't use story boards but you said that's OK in your comment. Hopefully my sample code helps you.

这是一个带有子类化 UITableViewController 的简单示例,其中填充了我的示例代码中的 NSArray (NSMutableArray)。它不使用故事板,但您在评论中说可以。希望我的示例代码对您有所帮助。

Header:

标题:

@interface MainTableViewController : UITableViewController 
{
    NSMutableArray *_items;
}

@end

Implementation:

执行:

@implementation MainTableViewController

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Lifetime
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) 
    {
        // datastore
        _items = [[NSMutableArray alloc] init];
        for (int index=0; index < 5; index++) 
        {
            [_items addObject:[NSString stringWithFormat:@"item #%d", index]];            
        }
    }
    return self;
}

- (void)dealloc
{
    [_items release];
    [super dealloc];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Table View DataSource
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // a typical table has one section
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // number of rows
    return [_items count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // NSIndexPath contains an array of indexes.  For UITableView:
    //    indexAtPosition:0 is the section number
    //    indexAtPosition:1 is the row number

    // create an identifier for this type of cell
    static NSString *CellIdentifier = @"Cell";

    // get a cell of this type from the re-use queue or create one
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) 
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // Configure the cell...
    NSString *title = [_items objectAtIndex:[indexPath indexAtPosition:1]];
    [[cell textLabel] setText:title];
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];

    return cell;
}


// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    {
        // Delete the row from the data source
        NSLog(@"delete section: %d rol: %d", [indexPath indexAtPosition:0], [indexPath indexAtPosition:1]);
        [_items removeObjectAtIndex:[indexPath indexAtPosition:1]];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) 
    {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        NSLog(@"insert section: %d rol: %d", [indexPath indexAtPosition:0], [indexPath indexAtPosition:1]);        
    }   
}

// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    NSString *fromItem = [_items objectAtIndex:[fromIndexPath indexAtPosition:1]];
    [_items removeObjectAtIndex:[fromIndexPath indexAtPosition:1]];
    [_items insertObject:fromItem atIndex:[toIndexPath indexAtPosition:1]];
}

// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark UITableViewDelegate
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"selected section: %d rol: %d", [indexPath indexAtPosition:0], [indexPath indexAtPosition:1]);

    // get the selected cell
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];

    // navigate to detail
    DetailedTableViewController *detailedView = [[DetailedTableViewController alloc] init];
    [[self navigationController] pushViewController:detailedView animated:YES];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark View lifecycle
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    [[self navigationItem] setRightBarButtonItem: [self editButtonItem]];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

回答by Hubert Kunnemeyer

The reason it crashes is that in the storyboard you have to change the tableview to dynamic prototypes instead of static cells. For some reason Static Cells is the default setting. Once you get the hang of the Storyboards it's great, especially when dealing with tableviews. Your initial View is set up as the NavigationController which has your MasterviewController as the RootViewController, so it's being loaded as the firstView. Click on the TableView in the MainStoryboard and change the Cels to Dynamic Prototypes or it will use the static ones that you create right in the storyboard. You can make custom cells right on the tableview in the storyboard. One more thing to note is the re-use identifier has to be set to the same name in the storyboard and the TableViewController. You can also just up the count of static cells to the number you want if you know it will always be the same.

它崩溃的原因是在故事板中,您必须将 tableview 更改为动态原型而不是静态单元格。出于某种原因,静态单元格是默认设置。一旦你掌握了 Storyboards 的窍门,它就很棒,尤其是在处理 tableviews 时。您的初始视图设置为 NavigationController,其中 MasterviewController 作为 RootViewController,因此它作为 firstView 加载。单击 MainStoryboard 中的 TableView 并将 Cels 更改为动态原型,否则它将使用您在故事板中创建的静态原型。您可以在故事板的 tableview 上制作自定义单元格。需要注意的另一件事是重用标识符必须在故事板和 TableViewController 中设置为相同的名称。