如何在iOS中创建具有动态值的UIButtons网格?

时间:2014-08-12 15:54:26

标签: ios objective-c uibutton

我正在尝试创建一个UIButtons网格。行和列值是动态的。我知道如何创建网格。但是使用动态值制作它是问题。

 -(void)makeLayoutWithMinRow:(int)minRow maxRow:(int)maxRow minColumn:(int)minColumn maxColumn:(int)maxColumn {

    NSInteger intLeftMargin = 10; // horizontal offset from the edge of the screen
    NSInteger intTopMargin  = 10; // vertical offset from the edge of the screen
    NSInteger intYSpacing   = 30; // number of pixels between the button origins (vertically)
    NSInteger intXTile;
    NSInteger intYTile;

    NSInteger width;

    width = ((self.layoutView.frame.size.width-(maxColumn * 5))/maxColumn);
    for (int y = minRow; y < maxRow; y++)
    {
        for (int x = minColumn; x < maxColumn; x++)
        {
            intXTile = (x * width) + intLeftMargin;
            intYTile = (y * intYSpacing) + intTopMargin;
            UIButton *buttons[x][y] = [[UIButton alloc] initWithFrame:CGRectMake(intXTile, intYTile, width, 15)];
            //Here I get error : Variable-sized object may not be initialised.

            [self.layoutView addSubview:buttons[x][y]];
        }
    }
}

我确实尝试了下面Cornelius建议的选项,将按钮存储在数组中。

 sButton = [[UIButton alloc] initWithFrame:CGRectMake(intXTile, intYTile, width, 15)];
 [buttons addObject:sButton]; 

在这种情况下如何添加这些按钮进行查看?

for (UIButton *obj in buttons) {
    [self.layoutView addSubview:obj];    //Doesn't work

}

6 个答案:

答案 0 :(得分:5)

  

这是取代UICollectionView的那个。我试过了   PSTCollectionView它会为您提供预期的结果。试试这个。

You can use PSTCollectionView.

答案 1 :(得分:4)

使用UICollectionView创建此类网格。

Here是一个教程。对于您的情况,在本教程中它是UIButton而不是UIImageView。

答案 2 :(得分:3)

这里似乎你想要实现的是稍后查找按钮。

因此,您需要在实例上使用变量(或属性)来保存引用,而不仅仅是创建过程中的局部变量。

有很多方法可以解决您的问题,一种简单而有效的存储引用的方法是'NSMutableDictionary'。

在您的班级中声明一个属性:

@property (nonatomic, strong) NSMutableDictionary *buttonDictionary;

在循环中设置:

_buttonDictionary = [[NSMutableDictionary alloc] init];

在循环中,编码x / y位置,例如使用NSIndexPath,滥用行/部分:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:y inSection:x];

创建按钮并添加到词典和超级视图中:

UIButton *freshButton = [UIButton buttonWithType:...]; // Much better than initWithFrame
freshButton.frame = ...;
_buttonDictionary[indexPath] = freshButton;
[self.layoutView addSubview:freshButton];

如果您想稍后通过x / y索引查找按钮,只需执行

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:y inSection:x];
UIButton *requestedButton = _dictionary[indexPath];

请注意,我在此处使用词典[]语法 - 您可以使用经典方法objectForKey:setObject:forKey:

答案 3 :(得分:1)

您可以使用UICollectionView并根据需要设置动态值或根据您的要求自定义。这是开发网格视图的非常简单有效的方法。在这里,我解释了一个简单的网格视图代码:

Like this :

@interface DashboardViewController : AbstractController <UICollectionViewDataSource, UICollectionViewDelegate>{
  NSMutableArray *dataSource;

}
@property (nonatomic, strong) UICollectionView *dashboardCollectionView;
@property (nonatomic, strong) ModulesDataModel *modulesDataModel;
@end

/*****************.m********************/
- (void)viewDidLoad {

    [super viewDidLoad];


UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
layout.scrollDirection = UICollectionViewScrollDirectionVertical;

_dashboardCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 135, 1024, 537) collectionViewLayout:layout];
    [_dashboardCollectionView setDataSource:self];
    [_dashboardCollectionView setDelegate:self];

    [_dashboardCollectionView registerClass:[CellMaster class] forCellWithReuseIdentifier:@"Reuse"];
    [_dashboardCollectionView setBackgroundColor:[UIColor clearColor]];

    [self.view addSubview:_dashboardCollectionView];

    dataSource = [NSMutableArray arrayWithArray:@"your objects"];
}

#pragma mark - Collection View Datasource and Delegate Methods

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return  UIEdgeInsetsMake( 22.0,  22.0,  22.0,  22.0);

}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{

    return 22.0f;

}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{

    return 15.0f;

}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(312,150);
}
- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return dataSource.count;
}

- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
        // Find the enum for this module and load the correct tile
    self.modulesDataModel = [dataSource objectAtIndex:indexPath.item];
     CellMaster * cell;
    cell = (CellMaster *)[collectionView dequeueReusableCellWithReuseIdentifier:@"Reuse" forIndexPath:indexPath];

    cell.tag = indexPath.item;

    cell.iconImage.image = [UIImage imageNamed:@""];
    cell.lblModuleName.text = self.modulesDataModel.moduleName;
    cell.lblModuleName.textColor = self.modulesDataModel.color;

    cell.btnInfo.tag = indexPath.item;
    [cell.btnInfo addTarget:cell action:@selector(didPressInfoIcon:) forControlEvents:UIControlEventTouchUpInside];

    cell.delegate = self;

    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
        // Enum for tile that was clicked


    self.modulesDataModel = [dataSource objectAtIndex:indexPath.item];
 }


Hope it would help you.

答案 4 :(得分:1)

我对你的代码进行了一些调整,并使其适用于此: 您必须手动初始化该阵列:这意味着您必须说明它有多大

@interface ViewController ()
@property (nonatomic) UIView *layoutView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.layoutView = [[UIView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.layoutView];
    [self makeLayoutWithMinRow:0 maxRow:5 minColumn:0 maxColumn:5];
}

- (UIColor *)randomColor {
    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
    UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
    return color;
}

-(void)makeLayoutWithMinRow:(int)minRow maxRow:(int)maxRow minColumn:(int)minColumn maxColumn:(int)maxColumn {

    NSInteger intLeftMargin = 10; // horizontal offset from the edge of the screen
    NSInteger intTopMargin  = 10; // vertical offset from the edge of the screen
    NSInteger intYSpacing   = 30; // number of pixels between the button origins (vertically)
    NSInteger intXTile;
    NSInteger intYTile;

    NSInteger width;
    id buttons[maxRow][maxColumn];

    width = ((self.layoutView.frame.size.width-(maxColumn * 5))/maxColumn);
    for (int y = minRow; y < maxRow; y++)
    {
        for (int x = minColumn; x < maxColumn; x++)
        {
            intXTile = (x * width) + intLeftMargin;
            intYTile = (y * intYSpacing) + intTopMargin;
            UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(intXTile, intYTile, width, 15)];
            button.backgroundColor = [self randomColor];
            buttons[x][y] = button;
            [self.layoutView addSubview:buttons[x][y]];
        }
    }
}

@end

答案 5 :(得分:0)

你正在尝试创建一个按钮阵列或类似的东西吗?

UIButton *buttons[x][y] = [[UIButton alloc] initWithFrame:CGRectMake(intXTile, intYTile, width, 15)];

您真正想要做的是创建按钮对象,然后将其添加到数组中(如果您想在之后访问它,否则它足以将其添加为子视图):

// Outside the for loop, probably as an instance variable or property:
NSMutableArray *buttons = [[NSMutableArray alloc] init];

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(intXTile, intYTile, width, 15)];
[buttons addObject:button];

您甚至可能需要将该按钮数组放在另一个数组中以使多维方面正确,或者使用带有相应键的NSMutableDictionary。