2015-11-02 42 views
-1

我不是Objective-C的初學者,但我是UITableViewCell的新手。如何使用解開按鈕在uitableviewcell上創建複選標記?

我想讓用戶能夠通過按下按鈕在TableViewCell上創建一個複選標記。這裏是我想出的代碼,

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

    UITableViewCell *cellx = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 


    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(40, 5, 40, 40)]; 
    [button setTitle:@"Button" forState:UIControlStateNormal]; 
    [button setBackgroundColor:[UIColor greenColor]]; 
    [button setTintColor:[UIColor redColor]]; 
    [button setTag:indexPath.row]; 
    [cellx addSubview:button]; 
    [cellx setIndentationLevel:1]; 
    [cellx setIndentationWidth:45]; 

    if (button.touchInside == YES) 
    { 
     NSLog(@"Button Pressed"); 
     cellx.accessoryType = UITableViewCellAccessoryCheckmark; 
     [tableView reloadData]; 
    } 

    return cellx; 
} 

而且該代碼似乎並沒有爲我工作。

任何想法?

+0

'cellForRowAtIndexPath'僅在刷新/渲染單元格時調用。你需要捕獲你的按鈕,找出它在哪個單元上,在單元上設置一個屬性,記下它應該被檢查,然後刷新單元。 – Stonz2

回答

1

試試這個:

@interface TableViewController() 

@property (strong, nonatomic) NSMutableArray *selectedIndexPaths; 

@end 

@implementation TableViewController 

- (NSMutableArray *)selectedIndexPaths { 
    if (!_selectedIndexPaths) { 
    _selectedIndexPaths = [NSMutableArray array]; 
    } 
    return _selectedIndexPaths; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return 20; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 

    if ([self.selectedIndexPaths containsObject:indexPath]) { 
    cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    } else { 
    cell.accessoryType = UITableViewCellAccessoryNone; 
    } 

    return cell; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    if ([self.selectedIndexPaths containsObject:indexPath]) { 
    [self.selectedIndexPaths removeObject:indexPath]; 
    [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone; 
    } else { 
    [self.selectedIndexPaths addObject:indexPath]; 
    [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark; 
    } 
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; 
} 
1

的作品更好的策略是:

  • 創建UITableViewCell自定義子類,並建立它的界面 在IB使按鍵出現在加載時
  • 保留一組對象 其中每個對象表示您想在一個單元格中顯示的內容
  • 當按鈕被點擊,告訴你的控制器以更新匹配陣列對象說它 應檢查
  • 告訴您的表視圖重新加載數據,或者完全或改變的索引路徑在cellForRowAtIndexPath
  • ,只需更新按鈕爲 ,取決於匹配的數組項目。
相關問題