2015-06-04 105 views
1

您好,我想問一下如何以編程方式創建多個視圖並將它們顯示在屏幕上,我試過這個,但有些東西缺失。以編程方式創建多個視圖

int x,y; 

x= 0; 
y=50; 

for (int i=0; i<4; i++) 
{ 
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, 300, 100)]; 

view.backgroundColor = [UIColor redColor]; 


[self.view addSubview: view]; 

    y+=40; 
} 
+0

你有這個代碼的哪個方法? –

+0

你使用哪種方法?我試圖在swift中創建多個UIViews,但我認爲這樣做會覆蓋它並從superview中刪除前一個。 – TheeBen

回答

0
int x,y; 
x= 0; 
y=50; 

for (int i=0; i<4; i++) 
{ 
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, 300, 100)]; 

    view.backgroundColor = [UIColor redColor]; 
    view.layer.cornerRadius = 5.0f; 
    [self.view addSubview: view]; 
    y+=140; //y for next view should be height of previous view and margin between view 
} 
+0

謝謝,如何使它們成爲一個圓角矩形形狀? –

+0

嘗試設置'view.layer.cornerRadius' – Sujay

+0

你好,我想問你如何在拖動它時更新幀大小我已經試過這段代碼: { {UITouch * touch = [touches anyObject]; CGPoint thisTouch = [touch locationInView:[touch view] .superview]; CGPoint prevTouch = [touch previousLocationInView:[touch view] .superview]; CGFloat dx = thisTouch.x - prevTouch.x; (觸摸視圖] .frame.origin.x + dx <-500) {觸摸視圖] .frame = CGRectMake([觸摸視圖] .frame.origin.x + dx, [觸摸視圖])。 frame.origin.y, [touch view] .frame.size.width, [touch view] .frame.size.height); } –

0
int x,y; 

    x= 0; 
    y=50 
    for (int i=0; i<4; i++) 
    { 
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, 30, 30)]; 

    view.backgroundColor = [UIColor redColor]; 
    y+=40; 

    [self.view addSubview: view];  
    } 
2
int x,y,paddingX,widthOfView,HeightOfView; 

x= 0; 
y=50; 
paddingX = 10; 
widthOfView = 100; 
HeightOfView = 100; 

for (int i=0; i<4; i++){ 
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, widthOfView, HeightOfView)]; 
    view.backgroundColor = [UIColor redColor]; 
    [self.view addSubview: view]; 

    y+= widthOfView + paddingX; 
} 

下面的代碼可以幫助到您。