2013-07-31 132 views
1

當我的滾動視圖更寬時,我的單元格按鈕顯示出來了。我把它做得更小,我的按鈕也消失了。我已經玩過這個框架,但它似乎不工作。有什麼建議麼?UITableView -cell按鈕沒有顯示出來

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

static NSString *CellIdentifier = @"Cell"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease]; 

     UIButton*button= [UIButton buttonWithType:UIButtonTypeCustom]; 
     button.frame = CGRectMake(10.0, 0.0, 20,20); 
     [button setTitle:@"Tap" forState:UIControlStateNormal]; 
    button.backgroundColor= [UIColor blackColor]; 
     [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside]; 
     cell.accessoryView = button; 
     [cell.contentView addSubview:button]; 

} 

NSString *cellValue = [selection objectAtIndex:indexPath.row]; 
cell.textLabel.text = cellValue; 

return cell; 
+0

是否曾經調用過cell == nil分支?或者以不同的方式提問:您是否註冊了重用Idenitfier Cell的UITableViewCell類?或者你在使用故事板? –

+0

不使用筆尖。不知道您的註冊問題是什麼意思,但if語句被稱爲 –

+0

爲什麼您將此按鈕分配給附件視圖?據我的理解,這將使表使用按鈕,儘管它已經是一個子視圖,並將其作爲子視圖添加到附件視圖應該在的框架中。這可能就在可見框架之外。通過這樣做,作爲子視圖的現有關聯被刪除,因爲每個視圖在子視圖層次結構中一次只能一次。它也可能改變框架。您是否在調試和addSubview語句後嘗試調試或nsloging按鈕框架? –

回答

0

如果條件如你寫的,你必須在外部實現自定義按鈕。你將不得不寫 - (UITableViewCell的*)的tableView:(UITableView的*)的tableView的cellForRowAtIndexPath:(NSIndexPath *)indexPath方法如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString * CellIdentifier = @"Cell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier]; 

if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: CellIdentifier]; 
} 

//custom button outside if condition 

UIButton*button= [UIButton buttonWithType:UIButtonTypeCustom]; 
button.frame = CGRectMake(10.0, 0.0, 20,20); 
[button setTitle:@"Tap" forState:UIControlStateNormal]; 
button.backgroundColor= [UIColor blackColor]; 
[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside]; 
cell.accessoryView = button; 
[cell.contentView addSubview:button]; 

return cell; 

}

+0

爲什麼會這樣工作?這樣做時,每次重用表格單元格時,都會創建並添加一個新的UIButton實例。當用戶向下滾動一下時,最終會在每個單元格中出現按鈕,當然,所有這些按鈕都具有相同的框架。 –

+0

感謝您的幫助,但事實證明我忽略了我的桌子有多大。 –

0

眼下襬脫這種說法:

cell.accessoryView = button; 
+0

想一想 - 我還沒有嘗試過 - 設置accessoryView屬性後設置框架可能會有所幫助。 –