0

我不知道如何寻找这个问题的答案,所以我想我会在这里试试运气。

简而言之,我有一个 UIView 并以编程方式创建了一个 UIButton 以及一个作为子视图添加到按钮的 UIImageView ,发生的情况是,当我按下按钮时,它允许我添加图像并将其存储在按钮。

所以我的问题是:一旦完成,我怎样才能让另一个按钮/ImageView 出现在视图中,在第一个按钮旁边(或者在它向右填充屏幕后,出现在第 2 行第 1 列) ETC

提前谢谢你!

4

3 回答 3

1

您可以UICollectionView按照@Bernahard Harrer 的指出使用,也可以使用以下代码。此代码仅添加了两个按钮。如果您需要更多按钮或按钮数组,请实现以下代码并计算先前添加的按钮的大小,因为button1计算添加的高度/宽度button2

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    [self addButtons];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void) addButtons
{
    UIView *view = [self view];
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button1 setBackgroundImage:[UIImage imageNamed:@"buttonImage1"] forState:UIControlStateNormal];
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button2 setBackgroundImage:[UIImage imageNamed:@"buttonImage2"] forState:UIControlStateNormal];

[button1 sizeToFit];
[button2 sizeToFit];


CGFloat combinedWidth = (button1.frame.size.width) + (button2.frame.size.width) ;

//checking if combined width of both buttons is more than 320
if (combinedWidth>320) {
    CGFloat button1height = button1.frame.size.height;
    button1height = button1height + 10;
    [button2 setFrame:CGRectMake(button2.frame.origin.x, (button2.frame.origin.y + button1height), button2.frame.size.width, button2.frame.size.width)];
} else {
    //if combined width of both buttons is less than or equal to 320
    //this will place the buttons adjacent to each other.
    //The code may be modified accordingly if to add some distance between them
    CGFloat button1width = button1.frame.size.width;
    [button2 setFrame:CGRectMake((button1.frame.origin.x+button1width), button2.frame.origin.y, button2.frame.size.width, button2.frame.size.height)];
}

[view addSubview:button1];
[view addSubview:button2];
}@end
于 2013-07-23T10:06:12.147 回答
0

您可以尝试使用 UICollectionView 来解决此问题。

于 2013-07-23T07:36:58.040 回答
0
@interface ViewController (){

    NSInteger x;
    NSInteger y;
}

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    x = 4;y=100;


    // Do any additional setup after loading the view, typically from a nib.
}


- (IBAction)addViews:(id)sender {

    CGRect frame = CGRectMake(x, y, 40, 10);

    int offset = 30;

    x = (frame.origin.x + frame.size.width + offset);

    UIView *view = [[UIView alloc] initWithFrame:frame];
    [view setBackgroundColor:[UIColor redColor]];

    if (view.center.x+view.frame.size.width > 320) {
        y +=20;
        x = 4;
    }
    [view setFrame:frame];

    [self.view addSubview:view];



}

@end
于 2013-07-23T08:09:21.357 回答