2012-01-19 163 views
1

我需要以編程方式創建UIButton,然後將它放在創建的UIScrollView上,然後將UIScrollView放在UIView上。如果將這些元素添加到self.view中,則會顯示它們,但是當我想嵌套時,則不會顯示它們。 這是我到目前爲止有:將UIButton添加到UIScrollView,然後將UIScrollView添加到UIView

viewWithPictures=[[UIScrollView alloc] initWithFrame:self.bottomView.frame]; 
viewWithPictures.contentSize=CGSizeMake(160*[smallImagesFromGallery count], self.bottomView.frame.size.height); 

viewWithPictures.backgroundColor=[UIColor greenColor]; 
NSLog(@"Number of small images: %i",[smallImagesFromGallery count]); 

for(int i=0; i<[smallImagesFromGallery count]; i++) 
{ 
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom]; 

    btn.frame=CGRectMake(self.bottomView.frame.origin.x+i*160, self.bottomView.frame.origin.y, 150, 100); 

    [btn setBackgroundImage:[smallImagesFromGallery objectAtIndex:i] forState:UIControlStateNormal]; 
    if (btn==nil) { 
     NSLog(@"Button is nil"); 
    } 
    btn.tag=i; 
    [btn addTarget:self action:@selector(viewLargeVersion:) forControlEvents:UIControlEventTouchUpInside]; 
    [viewWithPictures addSubview:btn]; 



} 
[bottomView addSubview:viewWithPictures]; 

回答

1

當您設置將成爲子視圖的視圖的框架時,您需要引用將被添加到視圖的邊界。因此,我認爲你需要改變幾行:

viewWithPictures=[[UIScrollView alloc] initWithFrame:self.bottomView.frame]; 

應該是:

viewWithPictures=[[UIScrollView alloc] initWithFrame:self.bottomView.bounds]; 

btn.frame=CGRectMake(self.bottomView.frame.origin.x+i*160, self.bottomView.frame.origin.y, 150, 100); 

應該是:

btn.frame=CGRectMake(i*160, 0, 150, 100); 
0

很難說沒有代碼的其餘部分,但它可能僅僅是因爲你沒有加入你的容器視圖(bottomView)你的看法?您可以通過在年底加入該做的事:[self.view addSubview: bottomView]

+0

謝謝,已經解決=) –

1
viewWithPictures=[[UIScrollView alloc] initWithFrame:self.bottomView.frame]; 

viewWithPictures=[[UIScrollView alloc] initWithFrame:CGRectMake(0,0,self.bottomView.frame.size.width,self.bottomView.frame.size.height)]; 

btn.frame=CGRectMake(self.bottomView.frame.origin.x+i*160, self.bottomView.frame.origin.y, 150, 100); 

btn.frame=CGRectMake(i*160, self.bottomView.frame.origin.y, 150, 100); 

這僅僅是一個建議。