我在哪里将UITableViewCell添加到此UITableView的SECOND部分?

时间:2012-12-04 20:28:05

标签: uiview uitableview

这里会有很多代码,为此我道歉,但问题是我很难通过这个程序,并确定这个东西在哪里创建UITableView的部分。

这是从“iOS编程:大书呆子牧场指南”开始的桌面视图练习开始,我决定更多地探索这个,所以我在Illustrator中创建了一些图像并去了城镇。

我已成功创建:

  • UIView

  • UITableView和UITableViewCell在ONE SINGLE SECTION中,填充了“Items”,它们只是随机生成的字符串,如书中的示例所示。 (随机形容词,随机名词,随机序列号等)

  • 点按时更改为突出显示状态的杂项按钮

  • 在第一个也是唯一一个显示更多按钮似乎工作正常的部分之后的页脚

我现在尝试做的就是练习,将这些随机生成的一半字符串项目中的一半放在表格视图单元格中,然后将它们放在表格的第2部分中视图。看起来像一个相对简单的任务,但我无法弄清楚在哪里/如何做到这一点。我已经阅读了文档,我想我可能需要实现insertSections:withRowAnimation:方法,但我无法在任何地方找到一个示例,它给我一个关于如何以一种在我的意义上有意义的方式实现它的线索程序

快捷方式 - 希望 - 我相信问题将出现在这篇帖子底部的ItemsViewController.m文件中。 ItemStore类只是一个名为'allItems'的数组,它保存我之前描述的随机生成的字符串项。对于我正在尝试做的事情,没有什么重要的事情似乎发生在AppDelegate文件中。任何帮助,将不胜感激。非常感谢提前。

ItemStore.h

#import <Foundation/Foundation.h>

@class Item;

@interface ItemStore : NSObject {
    NSMutableArray *allItems;
}

+(ItemStore *)sharedStore;
-(NSMutableArray *)allItems;
-(Item *)createItem;

@end

ItemStore.m

#import "ItemStore.h"
#import "Item.h"

@implementation ItemStore

// create the singleton ItemStore
+(ItemStore *)sharedStore {
    static ItemStore *sharedStore = nil;
    if (!sharedStore)
        sharedStore = [[super allocWithZone:nil] init];        
    return sharedStore;
}

+(id)allocWithZone:(NSZone *)zone {
    return [self sharedStore];
}

-(id)init {
    self = [super init];
    if (self) {
        allItems = [[NSMutableArray alloc] init];
    }
    return self;
}

-(NSArray *)allItems {
    return allItems;
}

-(Item *)createItem {
    Item *p = [Item randomItem];
    [allItems addObject:p];

    return p;
}

@end

AppDelegate.h

#import <UIKit/UIKit.h>

@class ItemsViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ItemsViewController *viewController;

@end

AppDelegate.m

#import "AppDelegate.h"
#import "ItemsViewController.h"
#import "Item.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    ItemsViewController *itemsViewController = [[ItemsViewController alloc] init];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:itemsViewController];
    [[self window] setRootViewController:navController];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {}
- (void)applicationDidEnterBackground:(UIApplication *)application {}
- (void)applicationWillEnterForeground:(UIApplication *)application {}
- (void)applicationDidBecomeActive:(UIApplication *)application {}
- (void)applicationWillTerminate:(UIApplication *)application {}

@end

ItemsViewController.h

#import <Foundation/Foundation.h>

@interface ItemsViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

{
    UIView *underView;
    UITableView *ivarTableView;
}

@property (nonatomic, readwrite) UITableView *ivarTableView;

-(id)init;
-(id)initWithStyle:(UITableViewStyle)style;
-(void)insertSections:(NSIndexPath *)indexPath withRowAnimation:(UITableViewRowAnimation)animation;
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;

@end

ItemsViewController.m

#import "ItemsViewController.h"
#import "Item.h"
#import "ItemStore.h"

@implementation ItemsViewController

@synthesize ivarTableView;

-(void)viewDidLoad {
    [super viewDidLoad];

    CGFloat startingPoint = 33.0;
    CGRect bounds = self.view.bounds;
    bounds.origin.y = startingPoint;
    bounds.size.height -= startingPoint;

    self.ivarTableView = [[UITableView alloc] initWithFrame:bounds style:UITableViewStyleGrouped];
    self.ivarTableView.dataSource = self;
    self.ivarTableView.delegate = self;
    self.ivarTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.ivarTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.ivarTableView];

    // create background, custom navigation bar, and a few other images/buttons, 
    // and some buttons that get placed in the footer.  all of these work fine.
    // ...

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection: (NSInteger) section
{
    // this method is a little unclear to me, but I've got everything in the footer working fine, so I haven't worried about it at this point.
    return 0.0;
}

// so far, init{} just creates a random amount of 'Items', which are just random strings so there's something to populate the UITableViewCells.
-(id) init {
    if (self) {
        int r = arc4random() % 10;
        NSLog(@"Number of cells in the table view should be:  %d", r);
        for (int i = 1; i <= r; i++) {
            [[ItemStore sharedStore] createItem];
        }
    }
    return self;
}

-(void)insertSections:(NSIndexPath *)indexPath withRowAnimation:(UITableViewRowAnimation)animation{
    // I think this is where I need to--create another section?--and send the second section the data that is going to be used in the second section's cells, but I'm having trouble tracing the flow of this program.
}

// Asks the delegate for the height to use for a row in a specified location and sends
// the appropriate size, based upon which image is going to be displayed for the particular cell.
// Top cell is a taller height, middle and bottom cell(s) are the same height.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSInteger lastRow = [self tableView:ivarTableView numberOfRowsInSection:1] - 1;
    NSInteger rowsAmount = [self tableView:ivarTableView numberOfRowsInSection:[indexPath section]];

    if (indexPath.row == 0 && rowsAmount != 1) {
        return 95.0;
    } else if (indexPath.row == 0 && rowsAmount == 1) {
        return 137.0;
    } /*end change*/ else if (indexPath.row == lastRow) {
        return 74.0;
    } else {
        return 74.0;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView
        cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];

    if (!cell) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                                   reuseIdentifier:@"UITableViewCell"];
    }

    NSInteger sectionsAmount = [tableView numberOfSections];
    NSInteger rowsAmount = [self tableView:ivarTableView numberOfRowsInSection:[indexPath section]];

    if (rowsAmount == 1) {
        cell.backgroundView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"cellTypeOne.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];

        cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"cellTypeOneTouched.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];

    } else if (rowsAmount == 2) {

        if ([indexPath section] == 0 && [indexPath row] == 0) {

            cell.backgroundView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"cellTypeOneMulti.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];

            cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"cellTypeOneMultiTouched.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];
        } else {

            cell.backgroundView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"cellBottom.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];

            cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"cellBottomTouched.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];
        }

    } else if (rowsAmount >= 3) {

        if ([indexPath section] == 0 && [indexPath row] == 0){

            cell.backgroundView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"cellTypeOneMulti.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];

            cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"cellTypeOneMultiTouched.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];            

        } else if ([indexPath section] == sectionsAmount - 1 && [indexPath row] == rowsAmount - 1) {

            cell.backgroundView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"cellBottom.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];

            cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"cellBottomTouched.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];

        } else {

            cell.backgroundView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"cellMiddle.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];

            cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"cellMiddleTouched.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];
            }
        }

    // gets rid of the white box that would bound the text of the cell
    [[cell contentView] setBackgroundColor:[UIColor clearColor]];
    [[cell backgroundView] setBackgroundColor:[UIColor clearColor]];
    [cell setBackgroundColor:[UIColor clearColor]];

    /* Set the text of the cell to the description of the item that is at the nth index of items, where n = row this cell will appear in on the tableView */
    Item *p = [[[ItemStore sharedStore] allItems] objectAtIndex:[indexPath row]];
    [[cell textLabel] setText:[p description]];
    [[cell textLabel] setHighlightedTextColor:[UIColor whiteColor]];
    [[cell textLabel] setTextColor:[UIColor blackColor]];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

/* return count of ItemStore's allItems array */
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[[ItemStore sharedStore] allItems] count];
}

// ...

@end

2 个答案:

答案 0 :(得分:1)

UITableView要求特定部分和行的单元格,调用方法

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

来自其“数据源”。

在这种情况下,数据源是ItemsViewController。所以在上面提到的方法中,其中一个参数是“indexPath”,它是指示返回单元格的部分和行的对象。

你可以知道是否要求第2节比较:

if(indexPath.section == 2)
{
    //Do something for section 2
}

编辑:

另外,要获得包含两个部分的表,您必须实现方法

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2; //Return the number of sections you what
}
在ItemsViewControlle.m中

祝你好运!

答案 1 :(得分:1)

我的代码中没有看到以下方法,这是您的tableview将调用的方法,以了解它应该创建多少部分。

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

最好让控制器成为UITableViewController的子类,而不是添加协议的UIViewController。它会为你节省很多错误。

insertSections:withRowAnimation: 
如果你需要在运行时添加一个部分,可以在你的tableview上直接调用