2014-01-24 17 views
0

我正在嘗試創建一個填充文本字段的表格單元格。但是,文本字段的數量永遠不會是固定的數量。我想我只是將陣列拍攝到表格單元格中,然後從那裏完成剩下的工作。iOS:添加數組來創建動態單元格

然而,我似乎無法弄清楚如何做到這一點...理想情況下,我將能夠訪問我的UITableViewCell- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier所需的數據。然後循環並分配必要數量的文本字段。

我在單元格中添加了myArray屬性,然後在上面的方法中做了alloc init,但仍然無法從我的視圖控制器訪問它。例如cell.myArray = ...

我該如何做到這一點?有更好的方法我應該這樣做嗎?這只是想到的第一種方式。任何幫助表示讚賞,謝謝你們。

EDIT(粗糙例):

//MyCell.h 

@interface ITDContactDetailsCell : UITableViewCell 
    @property (strong, nonatomic) NSMutableArray *myArray; 
@end 


//MyCell.m 

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { 
     self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
     if (self) { 
      _myArray = [[NSMutableArray alloc]init]; 
      //Do some stuff with array (like add UITextViews) 
     } 
} 

//MyViewController.m 

- (UITableViewCell*)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSString *cellIdentifier = @"ContactDetails4LineCell"; 
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath]; 
    //This doesn't even register 
    cell.myArray = [NSMutableArray arrayWithObjects: @"a", @"b", nil]; 

} 
+1

你能告訴你在哪裏指定數組和你在哪裏訪問數組分配後得到什麼叫什麼? – Mani

+0

我剛寫了一個粗略的例子。所有導入都是正確的,我可以訪問單元格中的其他東西(如UIViews)。然後,我再爲這些做一個addSubview,如果數組或類似的版本有相似的版本,我不會。 –

+1

我認爲你在正確的軌道上。但是你明白數組只是一個內存中的結構,而不是一個UI元素?這取決於您的自定義單元對該陣列做些什麼,以便用戶可以看到它,例如爲數組中的每個字符串創建UILabel並將這些標籤添加爲子視圖。 – danh

回答

1

您可以在ITDContactDetailsCell類上構建自己的setter。下面的簽名時,VC說cell.myArray = ...

- (void)setMyArray:(NSMutableArray *)array { 

    _myArray = array; // this + what ARC does to it is what the synthesized setter does 

    // here, we do something with the array so the user can interact with it 
    // labels are simpler, but textFields are the same idea 
    CGFloat x = 10, y = 10; 
    for (NSString *string in array) { 
     CGRect frame = CGRectMake(x,y,60,20); 
     UILabel *label = [[UILabel alloc] initWithFrame:frame]; 
     label.text = string; 
     [self addSubview:label]; 
     x += 60; 
    } 
} 
1

你必須改變流動。因爲

  • 它被稱爲第一個。 - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier並且由於empty array而沒有做任何事情。
  • cell.myArray = [NSMutableArray arrayWithObjects:@「a」,@「b」,nil]; 這將在第一個點後執行第二個,所以這也沒有什麼 。

更新:

試試這個..

在cell.h

-(void)addTextField; 

在cell.m

-(void)addTextField 
{ 
    // Do your stuff 
} 

在您的視圖 - 控制

- (UITableViewCell*)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSString *cellIdentifier = @"ContactDetails4LineCell"; 
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath]; 
    //This doesn't even register 
    cell.myArray = [NSMutableArray arrayWithObjects: @"a", @"b", nil]; 
    [cell addTextField]; 

} 
+0

感謝您的幫助,但事實證明這只是一個Xcode故障。重新啓動,我現在可以訪問cell.myArray(這個例子很粗糙)。 –

相關問題