2012-05-21 31 views
0

這是一個漫長的一天,我的大腦似乎並不想與我合作了......數學需要正確定位子視圖動態

我通過遍歷一個for循環的陣列中每個視圖子視圖。每個子視圖高度爲100像素。當數組中有1個項目時,視圖的y值需要設置爲0.當數組中有2個項目時,索引0處的視圖需要具有100的y值,並且索引處的項目1需要有ay值爲0.等等:

1 item: 0 = 0 
2 items: 0 = 100, 1 = 0 
3 items: 0 = 200, 1 = 100, 2 = 0 
4 items: 0 = 300, 1 = 200, 2 = 100, 3 = 0 

我需要能夠根據數組中的項目數量正確動態地處理這個問題。這裏是我到目前爲止的代碼:

for (int i = 0; i < [subViews count]; i++) { 
    NSView *v = (NSView *)[subViews objectAtIndex:i]; 
    [v setFrameOrigin:NSMakePoint(copy.view.frame.origin.x, i * 100)];//This gives me the opposite of what I want... 
} 

謝謝!

回答

1
int n = [subViews count]; 
for (NSView *v in subViews) { 
    n--; 
    [v setFrameOrigin:NSMakePoint(copy.view.frame.origin.x, n * 100)]; 
} 
+0

+1簡單而正確。希望我能想到這一點! – Lizza

1

循環之前插入這樣的:
int subviewCount = [subViews count];

而且[subViews objectAtIndex: (subviewCount - i - 1)]而不是[subViews objectAtIndex: i]

1

這將工作:

y = 100 * ([subViews count] - 1 - i) 

此外,僅供參考,請嘗試使用以下格式for循環:

for(NSView *thisView in subViews) 
{ 
    int i = [subViews indexOfObject:thisView]; //To get the "i position" 
    //The rest of the code can be the same 
} 

這樣做的原因是因爲,如果子視圖是空的,一個for(int i = 0; i < [subViews count]; i++)循環將至少運行一次,而崩潰,當你執行NSView *v = (NSView *)[subViews objectAtIndex:i];

for(NSView *thisView in subViews)如果子視圖爲空,將不會執行。

+0

如果您必須搜索每個對象的數組,則快速枚舉不再是非常快速的。更好地跟蹤指數(見我的答案)。 – LaC

+0

你是對的;雖然我建議這是爲了防止索引超出界限的錯誤。獲得我的價值的代碼行是因爲提問者在他的代碼中使用了我。 – Sid

相關問題