iOS中的网格视图

时间:2010-02-15 10:37:30

标签: ios iphone uitableview ipad gridview

我想在我的iPhone应用程序中创建一个类似于iPad photos app中显示的网格视图。是否有可用于添加此类功能的库或框架(非SDK)?理想情况下,我想最终开发一个iPad版本的应用程序,其中网格将是3个项目宽的纵向和4个横向,但是目前我想要2个宽的纵向和3个宽的景观。

我能想到的唯一方法是通过继承UITableView并拥有一个创建2或3项的自定义单元格。然而,这似乎很混乱,我相信有更好的方法。

一个典型的项目将有一个图片,标签和按钮 - 没有太复杂。

6 个答案:

答案 0 :(得分:25)

对于iOS 6及更高版本,我建议使用UICollectionViewPSTCollectionView

  

目标是在iOS 4/5上使用PSTCollectionView作为后备和   在iOS6上切换到UICollectionView。我们甚至使用某些运行时技巧   在运行时为旧版iOS创建UICollectionView。   理想情况下,您只需链接文件,一切都适用于旧版本   系统

在2010年,我推荐了AQGridView

答案 1 :(得分:10)

我知道这已经很老了,但我正在寻找答案并测试了几种解决方案。我发现GMGridView是最好的,最不错的解决方案之一。请查看https://github.com/gmoledina/GMGridView

答案 2 :(得分:9)

你仍然可以使用UITableView,你不需要将它子类化。就像你说的,所有你要做的就是创建自己的自定义单元格,这并不复杂。一点都不乱:)

答案 3 :(得分:2)

要在表视图中创建简单的网格视图,请创建类“GridViewCell”并在头文件中添加:

@interface GridViewCell : UITableViewCell

@property (nonatomic, strong)  UIButton *column1;
@property (nonatomic, strong)  UIButton *column2;
@property (nonatomic, strong)  UIButton *column3;

@end
<。>在.m文件中添加以下代码:

#define CELL_WIDTH 100
#define CELL_HEIGHT 80

#import "GridViewCell.h"

@implementation GridViewCell

@synthesize column1, column2, column3;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
    column1 = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, CELL_WIDTH, CELL_HEIGHT)];
    [self addSubview:column1];
    column2 = [[UIButton alloc] initWithFrame:CGRectMake(CELL_WIDTH+ 10, 5, CELL_WIDTH, CELL_HEIGHT)];
    [self addSubview:column2];
    column3 = [[UIButton alloc] initWithFrame:CGRectMake(CELL_WIDTH + CELL_WIDTH + 15, 5, CELL_WIDTH, CELL_HEIGHT)];
    [self addSubview:column3];
}
return self;
}

@end

当您创建表时,在委托cellForRowAtIndexPath中使用新类“GridView”:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    GridViewCell *cell = (GridViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[GridViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    [cell.column1 setBackgroundColor:[UIColor blackColor]];
    [cell.column2 setBackgroundColor:[UIColor blackColor]];
    [cell.column3 setBackgroundColor:[UIColor blackColor]];

    return cell;
}

答案 4 :(得分:1)

NRGridView似乎是最好的方式。你可以找到它here

它具有与UITableView类似的方法。可以根据需要定制单元格。

答案 5 :(得分:-1)

我建议使用自定义UITableViewCells。在iOS 5中,您不必将它们子类化。 只需将tableView添加到项目中,使用Xcode将原型单元格(=自定义单元格)添加到tableView,为它们提供唯一标识符,并在cellForRowAtIndexPath中使用此标识符来出列并实例化自定义单元格。然后设置单元格并将其返回。