我有兩個不同的表並排,以允許用戶選擇月份和年份組合。每個表都填充了來自兩個不同陣列的值。 monthsArray的值爲'01' - '12',yearsArray的值爲'2014' - '2023'。我已經驗證了數組保存了正確的值。UITableView重複前兩個值
表視圖高度僅足夠大,一次顯示一行一行。隨着用戶滑動表格以顯示後續值,數組地點0和1處的值將在兩個表中重複。例如,隨着月份表向上滾動,該序列重複:01 02 01 02 01 02 ...顯示了正確的總行數(12),但是在第二個位置之後這些值是錯誤的。這裏是一個屏幕截圖:
這裏是代碼:
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView.frame.size.width == MONTH_COLUMN_WIDTH) return 12;
else return [self.yearsArray count];
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
NSLog(@"indexPath: %@", indexPath);
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
cell.backgroundColor = [UIColor colorWithRed:DARK_BLUE_RED_COMPONENT green:DARK_BLUE_GREEN_COMPONENT blue:DARK_BLUE_BLUE_COMPONENT alpha:1.0f];
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
// add a label for the segment name
UILabel *label;
if (tableView.frame.size.width == MONTH_COLUMN_WIDTH) {
// this is the table to select the expiration month
label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,MONTH_COLUMN_WIDTH,EXPIRATION_ROW_HEIGHT)];
label.text = [self.monthsArray objectAtIndex:indexPath.row];
label.textAlignment = NSTextAlignmentCenter;
} else {
// this is the table to select the expiration year
label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,YEAR_COLUMN_WIDTH,EXPIRATION_ROW_HEIGHT)];
label.text = [self.yearsArray objectAtIndex:indexPath.row];
label.textAlignment = NSTextAlignmentCenter;
}
[label setFont:[UIFont fontWithName:DEFAULT_FONT size:13.0f]];
label.textColor = [UIColor whiteColor];
[cell addSubview:label];
}
return cell;
}
這裏是NSLog的輸出作爲予通過左表滾動:
indexPath:{長度= 2,path = 0 - 0}
indexPath:{length = 2,path = 0 - 1}
indexPath:{length = 2,path = 0 - 2}
indexPath:{length = 2,path = 0 - 3}
indexPath:{length = 2,path = 0 - 4}
indexPath:{length = 2,path = 0 - 5}
indexPath:{長度= 2,路徑= 0 - 6}
indexPath:{長度= 2,路徑= 0 - 7}
indexPath:{長度= 2,路徑= 0 - 8}
indexPath:{長度= 2,路徑= 0 - 9}
indexPath:{長度= 2,路徑= 0 - 10}
indexPath:{長度= 2,路徑= 0 - 11}
編輯:下面的評論是正確的,但只部分解決了我的問題。現在,當我在表格中滾動時,文本似乎在前面的文本之上呈現。到時候我到了最後一個單元格,這是一個混亂的爛攤子:
if(cell == nil){}塊的範圍看起來不正確,一旦表已經使可重用單元出列,我看不到標籤從數組中的數據更新的位置。 – 2014-10-01 20:50:12
謝謝。這部分解決了我的問題。你會看看編輯? – Alex 2014-10-01 21:07:05
由於單元格被重用,因此您將添加越來越多的UILabels作爲子視圖。我要麼繼承UITableViewCell來爲自定義UI提供訪問器,要麼使用可用的textLabel屬性來設置字符串。 – 2014-10-01 21:10:33