2011-11-17 39 views
1

我已經做了很多的測試和搜索,還是沒找到原因,我加入到UITableViewCell.contentViewUIButton將無法​​正常工作。我可以保證我做的一切正確,按鈕仍然不會回答TouchUpInside事件。爲什麼UITableViewCell.contentView中的UIButton將無法正常工作?

這樣的代碼將無法正常工作:

[self.contentView addSubview:theButton]; 

但是這會工作:

[self addSubview:theButton]; 

正如你可能預期,self是的UITableViewCell一個子類。並記錄到文檔,我們不應該總是添加東西到contentView

對不起,我英文不好。我希望我清楚地描述它。

+0

是否內容視圖=零,當你加了嗎? –

回答

1

嘗試的cellForRowAtIndexPath方法

UIButton *scanQRCodeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
scanQRCodeButton.frame = CGRectMake(260.0f, 6.0f, 45.0f, 25.0f); 
scanQRCodeButton.backgroundColor = [UIColor whiteColor]; 
[scanQRCodeButton setTitle:@"button" forState:UIControlStateNormal];  
[cell.contentView addSubview:scanQRCodeButton]; 

它會工作這段代碼。

0

如果你的UITableViewCell有一個客戶的高度(不是默認44.0f) 如果是這樣,你應該設置這樣的代碼:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *cellID = @"cellID"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID]; 
     cell.contentView.frame = CGRectMake(0, 0, tableView.width, [self tableView:tableView heightForRowAtIndexPath:indexPath]); 
     // add a UIButton that you create 
    } 
    return cell; 
} 

這個問題的原因是cell.contentView.size是默認的(320.f,44.0f),如果你的按鈕超過了矩形,那麼這個按鈕就不能接受這個事件,所以你應該自己設置cell.contentView.frame,就像我做的那樣。

祝你好運。

相關問題