Re: [問題] Custom Cell的幾個問題
※ 引述《tref (MFDA)》之銘言:
: 各位大大,小弟想請教2個問題:
: 1.當我 Custom Cell 時,但若到 DetailViewController 去修改Array的內容後 ,
: 返回上一頁 Cell 顯示的卻還是修改之前的內容,有確認Array的內容無誤
: aArray、bArray...等皆為NSMutableArray,請問到底是那裡出錯了??
因為你的reuse 有點問題
: 2.當Cell資料較多時,超出一個頁面所能呈現出的資料,EX:超過21筆 ,將畫面
: 上下捲動會出現其他資料沒錯,但資料的排序會亂掉,點選亂掉的資料進入
: DetailViewController也與Cell所呈現的資料不相符
: 請問各位到底是什麼問題?找不出原因苦惱中.....
: 謝謝
: Code如下:
: - (void)viewWillAppear:(BOOL)animated
: {
: [super viewWillAppear:animated];
: [self.tableView reloadData];
: }
到這裡沒太大問題
: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
: {
: static NSString *CellIdentifier = @"Cell";
: //增加LABEL
: UILable *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(105.0, 10, 125, 22.0)];
: [aLabel setText:[NSString stringWithFormat:@"%@",[aArray objectAtIndex:indexPath.row]]];
: UILable *bLabell = [[UILabel alloc] initWithFrame:CGRectMake(500.0,10.0, 125, 22.0)];
: [bLabell setText:[NSString stringWithFormat:@"%@",[bArray objectAtIndex:indexPath.row]]];
: UILable *cLabel = [[UILabel alloc] initWithFrame:CGRectMake(360.0, 10, 125, 22.0)];
: [cLabel setText:[NSString stringWithFormat:@"%@",[cArray objectAtIndex:indexPath.row]]];
: UILable *dLabel = [[UILabel alloc] initWithFrame:CGRectMake(230.0, 10, 125, 22.0)];
: [dLabel setText:[NSString stringWithFormat:@"%@",[dArray objectAtIndex:indexPath.row]]];
: UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
問題出在這,你alloc了一些label,設定了label的字串。
然後呼叫reuse,問題在於如果reuse成功,就不會加label到cell,
所以字串也沒設定到。
update:還有你的label拼錯了,我剛剛也拼錯XD
: if (cell == nil) {
: cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
: [[cell contentView]addSubview:aLabel];
: [[cell contentView]addSubview:bLabell];
: [[cell contentView]addSubview:cLabel];
: [[cell contentView]addSubview:dLabel];
: }
: return cell;
: }
比較好的方法是subclass UITableViewCell。
不過這裡提供一個比較hacky的方法。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * identifier = @"YouShouldSubclassIt";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
//alloc & init cell
//alloc & init labels
//這邊比較tricky 把labels 設tag
aLabel.tag = 1;
bLabel.tag = 2;
//add subview
}
UILabel * aLabel = (UILabel *)[cell viewWithTag:1];
UILabel * bLabel = (UILabel *)[cell viewWithTag:2];
a.text = @"what you want for a";
b.text = @"what you want for b";
return cell;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.128.223.100
※ 編輯: johnlinvc 來自: 220.128.223.100 (05/15 11:21)
推
05/15 12:27, , 1F
05/15 12:27, 1F
fix typo
※ 編輯: johnlinvc 來自: 220.128.223.100 (05/15 14:10)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):