我是iOS的新手。
我正在使用以下代码向控制器添加视图。
@interface ViewController : UIViewController <CollapseClickDelegate,UITextFieldDelegate> {
IBOutlet UIView *test1view;
IBOutlet UIView *test2view;
__weak IBOutlet CollapseClick *myCollapseClick;
}
我需要在下面创建50个不同的视图实例。我怎样才能做到这一点?我查看了子视图,但正如我在顶部所说,我是一个新手,无法弄清楚发生了什么。
-Name:
-AMOUNT:
-Percent:
答案 0 :(得分:1)
要以编程方式创建视图,请使用viewDidLoad:
UIViewController
- (void)viewDidLoad
{
[super viewDidLoad];
for(int i=0;i<50;i++){
//provide some initial frame, set the correct frames in viewWillLayoutSubviews:
CGRect frame = CGRectMake(0,i*10;100;5);
//create a new UIView, use your own UIView subclass here if you have one
UIView *view = [[UIView alloc] initWithFrame:frame];
//set it's backgroundColor in case you are copy&pasting this code to try it out, so you see that there are actually views added ;)
view.backgroundColor = [UIColor blueColor];
//add it to the viewController's view
[self.view addSubview:view];
//you might consider creating an NSArray to store references to the views for easier access in other parts of the code
}
}
要创建您在故事板中设计的视图,请使用此处所述的内容:https://stackoverflow.com/a/13390131/3659846
MyViewController *myViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"MyScene"];
[self.view addSubView:myViewController.theViewToAdd];
要从nib
文件创建视图,请使用此处描述的方法:https://stackoverflow.com/a/11836614/3659846
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"yourNib" owner:nil options:nil];
UIView *view = [nibContents lastObject]; //assuming the nib contains only one view
[self.view addSubview:view];
答案 1 :(得分:0)
for (int i = 0; i < 50; i++) {
UIView *someView = [UIView new];
// this positions each view one under another with height 40px and width 320px like a table
[someView setFrame:CGRectMake(0,40*i,320,40)];
// set other view properties
// put a UILabel on the view
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10,10,200,20)];
[view addSubview:label];
// set label properties
[self.view addSubview:someView]
}
请注意,框架相对于其父视图坐标系,您需要通过调用addSubview:方法将视图添加到其父视图。 - 好运