2015-10-30 47 views
-4

注意掉落的人:這個問題已經關閉很多天了。如果有人發現哪些是不必要的,請發表評論如何在tableview中動態添加段的行數?

我有一些文本框值& uiimage存儲在一個視圖控制器。我有另一個視圖控制器中的tableview。我想在tableview中使用nsuserdefaults來存儲值,並使用nsuserdefaults進行檢索,然後想要在用戶輸入時動態添加行?

+0

是的,它是可能的,你可以使用重新加載表視圖和添加表中的行或段的數量的運行時數 –

+0

請您詳細說明..? –

+0

「按用戶輸入動態添加行」是什麼意思?你想在運行時添加新的單元格,還是希望按用戶輸入的順序顯示數據? – NSNoob

回答

1

比方說,你有這樣的數據,像這樣的NSMutableArray

NSMutableArray *cellLabelValues = [[NSMutableArray alloc] initWithObjects: @"1",@"2",@"3",nil]; 

在你的tableView委託做到這一點:

- (NSInteger)tableView:(UITableView *)tableView 
numberOfRowsInSection:(NSInteger)section 
{ 
    return cellLabelValues.count; 
} 

你必須有一個按鈕或東西,接收用戶的意圖添加新的細胞。讓我們假設它調用這個方法:

-(void) addNewCell: 
    { 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Enter New Value" 
               message:@" " 
               delegate:self 
             cancelButtonTitle:@"Cancel" 
             otherButtonTitles:@"OK", nil]; 
alert.alertViewStyle = UIAlertViewStylePlainTextInput; 
[alert show]; 
    } 

並寫出UIAlertView的代表。請確保您作出的ViewController是UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { 
     if (buttonIndex == 1) { 
      NSString *value = [alertView textFieldAtIndex:0].text; 
      [cellLabelValues addObject:value]; 
      [tableView reloadData]; 
    } 
    } 

這裏發生的是,用戶點擊新的單元格按鈕。它需要用戶輸入。然後在將它添加到數組後將其重新加載。當它到達numberOfRowsInSection委託方法時,它看到該數組現在增加了1個。因此它將顯示一個額外的單元格。

+0

然後你將不得不使用'UITextField'。用它從用戶獲取文本。當條目結束時,將它添加到數組並重新加載tableview – NSNoob

+0

我剛剛編輯了代碼。現在,它會在運行時從用戶處獲得價值,並在按下好的時候將其顯示在表格中 – NSNoob

1

您可以使用文本字段中的字符串維護一個可變數組。

然後基於array.count你可以得到數組的大小。

- (NSInteger)tableView:(UITableView *)tableView 
numberOfRowsInSection:(NSInteger)section 
{ 
    return array.count 
} 

也不要忘記重新加載表視圖。

+0

@Uma當你來到你的'tableview'時,你的數組是否會被更新? – Rumin

+0

您是否在調用[tableView relaodData]方法之前將新單元格的數據添加到數組中? – NSNoob

+0

@NSNoob我無法添加到新單元格。 –

0

假設你有兩個UIViewControllersViewController1UITextFieldsViewController2UITableView

現在ViewController2聲明NSMutableArray *dataArray;

ViewController1移動到ViewController2

ViewController2 使用此功能

- (NSInteger)tableView:(UITableView *)tableView 
numberOfRowsInSection:(NSInteger)section 
{ 
    return dataArray.count; 
} 

這將有助於之前將其添加記錄。