繁体   English   中英

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

[英]How to create a grid of UIButtons with dynamic values in iOS?

我正在尝试创建一个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

}

这是替换UICollectionView 。我尝试过PSTCollectionView ,它给你预期的结果。 尝试这个。

您可以使用PSTCollectionView

使用UICollectionView创建此类网格。

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

看来你在这里尝试实现的只是稍后查找按钮。

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

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

在您的类中声明一个属性:

@property (nonatomic, strong) NSMutableDictionary *buttonDictionary;

在循环中设置它:

_buttonDictionary = [[NSMutableDictionary alloc] init];

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

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

创建按钮并添加到您的字典和superview:

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:而不是。

您可以使用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.

我对你的代码进行了一些调整,并使其工作:你必须手动初始化该数组:这意味着你必须说它会有多大

@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

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

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM