2015-11-06 107 views
1

我想在滾動視圖中顯示一些圖像,但我遇到了一些問題。在ScrollView中顯示圖像

以下是我有:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    myObject = [[NSMutableArray alloc] init]; 

    [myObject addObject:@"tut_5.jpg"]; 
    [myObject addObject:@"tut_2.jpg"]; 
    [myObject addObject:@"tut_3.jpg"]; 
    [myObject addObject:@"tut_4.jpg"]; 

    pageControlBeingUsed = NO; 


    CGRect screenRect = [[UIScreen mainScreen] bounds]; 
    CGFloat screenWidth = screenRect.size.width; 
    CGFloat screenHight = screenRect.size.height; 

    for (int i = 0; i < [myObject count]; i++) { 
     CGRect frame; 
     frame.origin.x = self.takeTourScrollView.frame.size.width * i; 
     frame.origin.y = 0; 
     frame.size = self.takeTourScrollView.frame.size; 

     NSString *val = [myObject objectAtIndex:i]; 


     UIImage* theImage = [UIImage imageNamed:val]; 


     UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(screenWidth*i,0,185 ,284)]; 


     img.image = theImage; 

     [self.takeTourScrollView addSubview:img]; 

    } 

首首圖像似乎是確定。

enter image description here

然後我向左滑動;我得到一個空白屏幕

enter image description here

我輕掃再次離開,然後當我看到我的第二張照片。對於所有4張圖像都是如此。

任何想法我做錯了什麼?

回答

3

我建議使用UITableView/UICollectionView這樣的行爲。你可以在每個單元格中設置圖像,它們將被重用 - 在內存管理方面會更好。

tableView將順便將所有元素放置在適當的位置(您只需要定義單元格或佈局的高度)。

它也將正確調整事件(例如電話輪換)。

此外,你應該儘量避免硬編碼的大小:

CGRectMake(screenWidth*i,0,185 ,284) 

您將在小/大設備的情況下失敗。在一段時間後維護代碼將是一件很痛苦的事情。

- 編輯 -

後@DuncanÇ張貼了他的答案,我注意到你正在尋找一個尋呼系統。您可以在UIPageViewControllerUICollectionView上構建自己的解決方案。不過你也可以使用第三方庫,我真的很喜歡這個:https://www.cocoacontrols.com/controls/bwwalkthrough。它有不同的動畫支持,併爲你做了很多東西:)。

3

有一些系統組件可以爲您提供您想要的更少的工作和更精緻的用戶體驗。 Vive在她的回答中提到,使用UICollectionView是一種可能性。我的建議是UIPageViewController。有一個來自Apple的示例應用程序PhotoScroller,它顯示瞭如何實現非常類似於您所描述的UI的UI。在Xcode文檔中搜索「PhotoScroller」以查找它。

+0

+1其實如果OP想要的東西就像一個尋呼系統,使用'UIPageViewController'比我的解決方案更好的主意。 – Vive

0

您已經設置了uiscrollview的x位置。不需要設置UIImageView的x位置。因爲您使用imageview作爲uiimagescrollview的子視圖。 此行更改爲

UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(screenWidth*i,0,185 ,284)]; 

UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(0,0,185 ,284)];