2013-06-03 93 views
0

我在「UITableViewCell」中使用自定義圖像作爲複選標記 - '[email protected]',但它顯示在單元格中的任何位置。任何人都可以建議如何使其僅顯示單個選定的單元格?所選行的自定義複選標記

這裏是我的代碼:實現你試圖做的是使用一個按鈕,設置背景圖片爲您的複選框

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 


    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
         reuseIdentifier:CellIdentifier]; 

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; 

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10,10, 300, 30)]; 
    [cell.contentView addSubview:label]; 
    label.text = [tableArr objectAtIndex:indexPath.row]; 
    label.font = [UIFont fontWithName:@"Whitney-Light" size:20.0]; 
    label.tag = 1; 
    UIImageView *checkmark = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"[email protected]"]]; 
    cell.accessoryView = checkmark; 
    return cell; 
} 
+0

你有一個屏幕截圖。我以幾乎相同的方式做了幾次。只需使用圖像創建UIImageView並將其分配給cell.accessoryView即可。你檢查了cell.accessoryView的框架嗎?它是什麼? –

+0

@CodeMonkey請在將來進行更完整的修改,修復帖子中的多個問題。此外,僅將「代碼塊」用於「代碼」。 – Undo

+0

當然可以。謝謝撤消。 –

回答

1

更少的代碼更好:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 


static NSString *CellIdentifier = @"Cell"; 

UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (!cell) { 
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
         reuseIdentifier:CellIdentifier]; 
[cell setSelectionStyle:UITableViewCellSelectionStyleNone]; 
} 


cell.textLabel.text = [tableArr objectAtIndex:indexPath.row]; 
cell.textLabel = [UIFont fontWithName:@"Whitney-Light" size:20.0]; 
return cell; 

}

UPDATE:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    lastIndexPath = indexPath; 
    [tableView reloadData]; 
} 


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { 
      if ([lastIndexPath isEqual:indexPath]) { 
       cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iphone-checkMark.png"]]; 
      } else { 
       cell.accessoryView = nil; 
      }  
} 

更新2:

//dont forget check for nil 
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
[defaults setValue:lastIndexPath forKey:@"lastIndexPath"]; 
[defaults synchronize]; 

NSIndexPath *lastPath = [defaults valueForKey:@"lastIndexPath"]; 
+0

有一些原因,你在使用單元格的自定義標籤,你是否正確地閱讀了這個問題,當前代碼工作正常,但它顯示每行/單元格上的複選標記,而不是我想要顯示覆選標記在Viewdidload上,並且一旦用戶點擊一行/單元格,單個複選標記將出現在最後選擇的行上。 – Anil

+0

錯誤:未知接收者'lastIndexPath';你的意思是'NSIndexPath'? – Anil

+0

添加新的類變量NSIndexPath * lastIndexPath – NeverBe