2014-07-08 62 views
0

我是iOS新手。如何多次使用視圖?

我使用下面的代碼向控制器添加視圖。

@interface ViewController : UIViewController <CollapseClickDelegate,UITextFieldDelegate> { 

    IBOutlet UIView *test1view; 
    IBOutlet UIView *test2view; 

    __weak IBOutlet CollapseClick *myCollapseClick; 
} 

我需要創建位於下方的視圖的50個不同的實例。我怎樣才能做到這一點?我研究了子視圖,但正如我在頂部所說,我是一個新手,無法弄清楚發生了什麼。

-Name:
-AMOUNT:
-Percent:

+0

如果您使用視圖50次,您確定要爲每個視圖使用IBOutlets?您可以創建一個自定義UIView,以編程方式在頁面上插入。 – LyricalPanda

+0

我其實想編程50。我會怎麼做?我目前正在使用名爲CollapseClick的插件,我只知道如何通過上面的代碼添加視圖。我現在將研究自定義類。感謝您的意見。 –

回答

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的視圖添加到它的父視圖:方法。 - 好運氣

1

以編程方式創建您的看法,用你的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 
    } 
} 

viewDidLoad:要創建一個像這裏所描述的,你在故事板使用的東西設計了一個觀點: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];