UIButton 點擊時無法附帶自身參數的解決辦法

UIButton的 taget函數只能是 不帶參數或者帶一個默認UIButton類型的參數.當把UIButton加入table的時候獲取點擊時候的行數就是個問題.

目前有兩個方法來處理:

1:用UIButton自身的tag    

也就是說在創建UIButton的時候設置tag爲tableview的index.row.這樣在回調函數裏面根據tag就可以處理.但是這個方法有個弊端就是如果tag被用來做tableview的動態加載標示,那就用第二種方法去解決了

        示例

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

{

NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d", indexPath.row];//這裏按照每個row來標示cell,所以每個cell都是獨立的,沒有複用,數量少的時候可以這麼處理

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];


   if(!cell)

    {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

    }


UIButton *btnBuy  = (UIButton*)[cell viewWithTag:indexPath.row];

    if(!btnBuy)

    {

XXXXX

btnBuy.tag =indexPath.row;

  [btnBuy addTarget:self action:@selector(onClickBuy:) forControlEvents:UIControlEventTouchUpInside];

}

[btnBuy setImage:XXXX];

return cell;

}

-(void)onClickBuy:(UIButton*)btn

{

    NSLog(@"點擊了第%d",btn.tag);

}


以上這種就可以獲取到當前點擊的行數.

2:複用cell的情況下的解決辦法:

解決辦法其實就給uibutton增加一個子類view,設置子類view的tag

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

{

NSString *CellIdentifier = @"Cell";//注意這裏這樣寫就是複用cell

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];


   if(!cell)

    {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

    }


UIButton *btnBuy  = (UIButton*)[cell viewWithTag:4000];

    if(!btnBuy)

    {

XXXXX

btnBuy.tag =4000;

  [btnBuy addTarget:self action:@selector(onClickBuy:) forControlEvents:UIControlEventTouchUpInside];

UIView *tagView = [[UIView alloc]init];

        tagView.tag = indexPath.row;

        [btnBuy addSubview:tagView];

        [tagView release];


}

[btnBuy setImage:XXXX];

return cell;

}

-(void)onClickBuy:(UIButton*)btn

{

    UIView *tagView = [[btn subviews] objectAtIndex:0];

    NSLog(@"點擊了第%d",tagView.tag);

}


這樣就可以繞過之前的阻礙繼續獲取當前點擊行數了.




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章