2013-07-19 26 views
3

在我的代碼中,我有一個表格視圖,其中有很多節按字母順序排序。我在錶行中有checkboxes(UIButton),我需要根據在行中輸入的相應狀態來檢查它們。我已經完成在IOS中獲取UITableView的行號

checkbutton.tag = indexpath.row; 

但當表格滾動和部分得到改變,我得到我的複選框方法中的前一節的狀態。任何人都可以幫助我。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CheckButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [CheckButton addTarget:self action:@selector(CheckBoxAction:)  forControlEvents:UIControlEventTouchUpInside]; 
    CheckButton.tag=indexPath.row; 
    //some other stuff 
    [cell.contentView addSubview:CheckButton]; 
} 

,這我CheckBoxAction

-(void)CheckBoxAction:(UIButton *)btn 
{ 
    tag = btn.tag; 
    NSDictionary *tagdict =[statusArray objectAtIndex:tag]; 
} 

現在的問題是,indexpath.row爲0時部分被改變,所以我不能在我CheckBoxAction訪問確切的行數。

+0

爲什麼在該事件中創建複選框按鈕,而不是在getCellForRowAtIndex或interface builder中創建? –

回答

2

使用此功能可以獲取當前點擊的行。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
CheckButton = [[UIButton alloc] init]; 

[CheckButton addTarget:self action:@selector(CheckBoxAction:)  forControlEvents:UIControlEventTouchUpInside]; 
CheckButton.tag=indexPath.row; 
[cell addSubview:CheckButton]; 
} 


-(void)CheckBoxAction:(id)sender 
{ 
    // Cast Sender to UIButton 
UIButton *button = (UIButton *)sender; 

// Find Point in Superview 
CGPoint pointInSuperview = [button.superview convertPoint:button.center toView:self.tableView]; 

// Infer Index Path 
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:pointInSuperview]; 

// Log to Console 
NSLog(@"selected Row : %d", indexPath.row); 
} 
1

//試試這個

CheckButton.tag = [[NSString stringWithFormat:@"%d%d",indexPath.section,indexPath.row] integerValue]; 

//在UITableView的

Set checkmark in UITableView

+0

當部分大於9並且部分中的行大於9時,這會變得糟糕。 –

0

試試這個下面鏈接以獲得邏輯,如何處理複選框你什麼在許多方面做錯了。所以,我不打算給你,你有確切的問題的解決方案,但更多的是指引:

  1. 首先,你是直接添加的複選框的單元格,這意味着你可以添加多個CheckButton到相同的單元格,如果你滾動UITableView幾次。

  2. 將checkButton直接添加到單元格中,而不是將其添加到cellForRowAtIndexPath中,這可以提高性能。

  3. 使用用戶單擊按鈕時將執行的塊。這樣您就可以捕捉到您的UIViewController的環境。您應該將該塊分配給單元格cellForRowAtIndexPath

+0

你能解釋一下如何直接在單元格中添加checkButton,而不是在cellForRowAtIndexPath中添加它 – Vikas

+0

你可以在你的Cell中添加'awakeFromNib'。或者,如果你沒有NIB,你可以添加它的init方法。但是,這不是對你的問題的具體回答,更多的是指導。 – Peres

+0

先生我不明白你可以提供一些鏈接,教程或任何類型的幫助直接在單元格上添加checkButton – Vikas