2011-09-08 25 views
0

我正在動態創建按鈕。並通過在不使用標籤的情況下在按鈕操作方法中傳遞參數

[newButton addTarget:self action:@selector(goToNew:)forControlEvents:UIControlEventTouchUpInside]; 

我想給從實現代碼如下參數(indexpath.row),但不希望使用標籤..因爲我需要這個標籤將保持相同的所有按鈕,如何傳遞的創建操作方法按鈕操作中的參數?

實際上,我在每個tableview單元格中添加按鈕,並且我想爲所有這些按鈕採取行動,但是如果我使用tag = indexpath.row並將其與動作一起使用,它將起作用,但疊加按鈕的問題會發生。希望標籤不變。

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

static NSString *CellIdentifier = @"Cell"; 
UIButton *btn; 

UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; 

    btn = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [btn addTarget:self action:@selector(goToNew:) forControlEvents:UIControlEventTouchUpInside]; 
    btn.tag = 55; 
    [cell.contentView addSubview:btn]; 

} 
else { 
    btn = (id)[cell.contentView viewWithTag:55]; 

} 

return cell; 

}

- (void) goToNew:(id)sender 

{
UIButton *b = (UIButton *)sender;
的UITableViewCell 細胞=(的UITableViewCell)並[b上海華];
int row = [msgTableView indexPathForCell:cell].row;
(@「row is :::%d」,row);

} 
+1

我不明白「但不想用標籤..」 – Maulik

+0

是的,我沒有....... – PJR

+0

看看我的答案在這裏:http://stackoverflow.com/questions/7399119/custom-uitableviewcell-button-action/14955341#14955341 – djskinner

回答

1

通過執行以下代碼,您將獲得indexPath.row並且無需設置按鈕標記。

- (IBAction)goToNew:(id)sender 
{ 
    UIButton *btn = (UIButton*) sender; 
    UITableViewCell *cell = (UITableViewCell*) [btn superview]; 
    NSIndexPath *indexPath = [tableView indexPathForCell:cell]; 
    int row = indexPath.row; 
} 
+0

但我怎麼能知道它是哪個按鈕...意味着在哪個單元格我的按鈕是,我與sender.tag得到它,但現在我怎麼能得到該整數值? – PJR

+0

使用btn.tag你可以得到標籤的按鈕 – Narayana

+0

我想做它沒有標籤..我希望標籤將保持不變。 – PJR

0
-(void)goToNew:(id)sender 

{ 
    UIButton *btnTemp = (UIButton *)[yourTableView viewWithTag:sender]; 
    int iTag = btnTemp.tag; 

} 
+0

爲此,當我創建我的按鈕我必須specpeciy mybtn.tag = indexpath.row,我是嗎?但我希望那個標籤是不變的,所以我想在沒有指定標籤的情況下創建buttom – PJR

+0

然後你可以使用按鈕標題(如果它唯一的)... – Maulik

+0

沒有按鈕的標題。只有圖像。我如何使用它? – PJR

1

您可以通過另一種說法爲使用不同forstate.Here按鈕設置標題,你可以通過indexpath作爲button.like

btn.tag=10; 
    [btn setTitle:[NSString stringWithFormat:@"%d",indexpath.row] forState:UIControlStateDisabled]; 
    [btn addTarget:self action:@selector(btnClick:)forControlEvents:UIControlEventTouchUpInside]; 

的標題,你會收到的參數作爲

-(void)btnClick:(id)sender 
{ 
UIButton* b = (UIButton*) sender; 
NSLog(@"tag=%d",b.tag); 
    //Below line will got indexpath in string formate.. 
NSLog(@"title =%@",[b titleForState:UIControlStateDisabled]); 
} 
相關問題