2012-07-13 235 views
0

我對iOS開發很新,我在這裏遇到問題,無法在其他地方找到解決方案。xCode動態添加字段

我需要動態生成的profileDetailViewController.m領域是的UIViewController類型,

場我要上查看存儲在陣列它看起來像這樣,

Array:(
     { 
     fieldName = Full Name; 
     value = Neil G.; 
    }, 
     { 
     fieldName = Aboutn me; 
     value = "a web dev.."; 
    }, 
     { 
     fieldName = State; 
     value = Colorado; 
    }, 
     { 
     fieldName = City; 
     value = Denver; 
    }, 
     { 
     fieldName = Website; 
     value = "http://google.com"; 
    }, 
     { 
     fieldName = College University; 
     value = "DSU"; 
    }, 
     { 
     fieldName = Graduation Year; 
     value = 2011; 
    } 
) 

我只是試圖使它像iPhone中的聯繫人, 最初加載頁面作爲顯示模式與編輯按鈕,所以當編輯模式它應該變成可編輯字段的形式。任何好的教程都會很棒。我會感謝你的幫助。謝謝。

回答

3

第一搶你的領域的數組的大小:

int fieldCount = [Array count];

然後創建一個wrapperView我們會放在一個滾動視圖,因爲我們都知道,你將有更多的領域比你能適應於屏幕!

UIView *wrapperView = [[UIView alloc] initWithFrame:self.view.frame]; 
[self.view addSubView:wrapperView]; 
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:wrapperView.frame]; 
[wrapperView addSubView:scrollView]; 

現在我要爲此目的添加一些標籤,但您可以輕鬆地製作它們的按鈕或您有什麼。我會讓他們有一個10像素的高度之間的高度。

所以現在我們需要設置了滾動的contentSize

double heightNeeded = 0; 
heightNeeded = fieldCount * 31; 
if(heightNeeded < scrollView.frame.size.height){ 
    heightNeeded = scrollView.frame.size.height; 
} 

現在我們可以告訴它滾動視圖內容大小需要多大的空間可以,然後添加的所有標籤。我將假設你的數組充滿了名爲Details的對象,它們有一個fieldName和一個Value,因爲你沒有真正指定。

[scrollView setContentSize:CGSizeMake(scrollView.frame.size.width,heightNeeded)]; 
int currentY = 0; 
for(Details *thisDetail in Array){ 
    UILabel *thisLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,currentY,scrollView.frame.size.width,21)]; 
    [thisLabel setLineBreakMode:UILineBreakModeWordWrap]; 
    thisLabel.numberOfLines = 0; 
    UILabel.text = [NSString stringWithFormat:@"%@: %@",thisDetail.fieldName,thisDetail.Value]; 
    [thisLabel sizeToFit]; 
    [scrollView addSubView thisLabel]; 
    currentY = currentY + thisLabel.frame.origin.y + thisLabel.frame.size.height + 10; 
} 

不知道你是否希望它們是這樣的標籤,但很容易改變。可能還有其他一些事情,比如實現UIScrollViewDelegate然後在某個地方執行,但我不確定。希望這可以幫助!

+0

感謝user1458968,你的解決方案是完美的..第二件事,我想讓字段從顯示切換到可編輯,所以當編輯按鈕按下它應該工作的形式..就像iPhone接觸..有沒有任何直接或者我只需要添加textFields而不是標籤。再次感謝.. – locateneil24 2012-07-13 22:32:07

+0

是啊,我會讓他們UITextFields,而不是切換'userInteractionEnabled'或任何它被稱爲。考慮將背景顏色更改爲灰色或不可編輯的時候,不確定它是否顯而易見,並且我現在不在xCode前的計算機前面 – jacerate 2012-07-13 23:15:50

+0

我錯了,還是可以通過計算得到'heightNeeded' 'fieldCount * 31'?所以你不需要for循環來添加31個fieldCount時間。 – 2014-05-15 09:25:08