2011-10-04 20 views
0

我有一個UIButton在UITableViewCell中...... 我想執行的UIButton的行動..執行行動的UITableView

我需要將數據發送到已註冊的@選擇方法此按鈕,以便我可以在用戶按此按鈕時執行操作。

如何做到這一點,雖然我發現(id) sender參數裏面的選擇器功能並不總是在cellForRowAtIndexPath函數中創建的原始按鈕。

裏面的cellForRowAtIndexPath功能:

UIImage* pdfImage = [UIImage imageNamed:@"icon_pdf.png"]; 
UIButton* pdfButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
[pdfButton setImage:pdfImage forState:UIControlStateNormal]; 
pdfButton.accessibilityHint = @"path/to/pdf/file"; 
pdfButton.frame = CGRectMake(0, 0, 40, 40); 
[pdfButton addTarget:self action:@selector(openUrlInBrowser:) forControlEvents:UIControlEventTouchUpInside]; 
cell.accessoryView = pdfButton; 

這裏的發送功能:

-(void) openUrlInBrowser:(id)sender 
{ 
    NSLog(@"%@", [sender class]); 
    NSString * url=[sender accessibilityHint]; 
    NSLog(@"%@",url); 
    NSLog(@"%@",sender); 
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]]; 
} 
+0

你想讓那個按鈕覆蓋整個單元嗎? – Bourne

+0

不,我不...... –

+0

這將有助於查看這些NSLog語句的結果。還有你的cellForRowAtIndexPath方法的其餘部分。 – jrturton

回答

1

希望我理解正確的問題 - 我通常在uitableview中添加的按鈕上定義一個標籤,這是該行的索引。在的cellForRowAtIndexPath:

[button setTag:indexPath.row]; 

你可以再賺回來的目標方法:

- (void) showdatabases:(id) sender { 
int row = [[sender valueForKey:@"tag"] intValue]; 
... 

而且使用查詢單元格中的數值爲您處理:

UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]]; 

另外,您可以通過訪問發件人的超級視圖獲得相同的結果,但我覺得這更難以調試。

0

我更喜歡使用:

-(void) openUrlInBrowser:(id)sender 
{ 
    UIButton * button = (UIButton *)sender; 
    NSString * url=[button.superview accessibilityHint]; 
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]]; 
} 

它不是在表

依賴於細胞的位置
+0

看到我的編輯請 –

+0

確定您的代碼,很明顯!我添加了其他解決方案 –