我不知道如何搜索这个问题的答案所以我想我会在这里试试运气。
简而言之,我有一个UIView并以编程方式创建了一个UIButton,并将一个UIImageView作为子视图添加到按钮中,当我按下按钮时,它允许我添加一个图像,它存储在按钮上。
所以我的问题是:一旦完成,我怎么能让另一个按钮/ ImageView出现在视图中,第一个按钮旁边(或者在它向右填充屏幕之后,出现在第二行) ,第1栏)等等
先谢谢你了!
答案 0 :(得分:1)
您可以使用@Bernahard Harrer指出的UICollectionView
,也可以使用以下代码。此代码仅添加两个按钮。如果您需要更多按钮或按钮数组,请实现以下代码并计算之前添加按钮的大小,因为计算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
答案 1 :(得分:0)
您可以尝试使用UICollectionView来解决此问题。
答案 2 :(得分: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