通過學習iOS開發 - 大書呆子牧場指南」(Conway和Hillegass) 章‘子類的UIView和UIScrollView的’;平移和尋呼
下面的代碼塊被鍵入的 - (BOOL)應用中:didFinishLaunchingWithOptions:方法混淆了一個簡單的分頁和平移示例。 OBJ-C
(HypnosisView - 在實際執行在屏幕上繪製一個定製類)。
無法理解下面的代碼:
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//-------Adding a scrool option-----------
CGRect screenRect=[[self window] bounds];
// create the UIScrollView to have the size of the window, matching its size
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:screenRect];
[scrollView setPagingEnabled:YES];
[[self window] addSubview:scrollView];
// create the HypnosisView with a frame that is twice the size of the screen (with a big
// width)
CGRect bigRect = screenRect;
bigRect.size.width *=2.0;
HypnosisView *view=[[HypnosisView alloc] initWithFrame:screenRect];
// add the HypnosisView as a subview of the scrollView istead of the window
[scrollView addSubview:view];
// move the ractangle for the other HypnosisView to the right, just off the screen
screenRect.origin.x = screenRect.size.width;
HypnosisView *anotherView = [[HypnosisView alloc] initWithFrame:screenRect];
[scrollView addSubview:anotherView];
// tell the scrollView how big its virtual world is
[scrollView setContentSize:bigRect.size];
所以我們的目標是創建一個寬度大於iphone屏幕的視圖實例。
首先,我們聲明瞭具有「窗口」範圍的新變量「screenRect」。
然後,我們正在創建一個「UIScrollView」的實例,其框架尺寸與窗口中的 「screenRect」相同。
使頁面啓用。
將我們新創建的「scrollView」添加到視圖層次結構中。 所以我們有父窗口和子窗口scrollView(它與我們的主窗口尺寸相同)
聲明一個新變量「bigRect」,並使其等於我們先前聲明的「screenRect」。
將bigRect的「width」屬性設置爲兩倍。
創建一個新的「視圖」對象,它是我們自定義的實際執行繪圖的催眠類的一個實例。我們將視圖的框架設置爲與我們的「screenRect」框架相同。
將我們新創建的「視圖」添加到視圖層次結構中。現在我們有3個層次結構:一個UIWindow - > UIScrollView中 - > HypnosysView
9.Now在這裏,我不明白這行代碼所做的和爲什麼我們需要它(screenRect.origin。 x = screenRect.size.width;)
10)。爲什麼我們要在下一行創建另一個HypnosisView實例? 11)。最後我們通知scrollView它的大小有多大。
謝謝埃德溫,我沒有想到我們必須創建另一個HypnosisView實例來填充我們的scrollView的其餘部分。 – 2013-03-14 21:20:41