0

我有一個UICollectionView,其單元全部佈局。在UICollectionViewCell中點擊一個UIButton

我有這個聲明爲一個子視圖:

@property (nonatomic, strong) UIButton *aButton; 

然後我有一個聲明在每個單元中,像這樣:

if (_aButton == nil) 
{ 
    _aButton = [UIButton buttonWithType:UIButtonTypeSystem]; 
} 

// Add in all _aButton info here 

[self.contentView addSubview:_aButton]; 

// Call to button pressed for button 

[_aButton addTarget:self action:@selector(aButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 

點擊按鈕的方法是像這樣:

- (IBAction) aButtonPressed:(UIButton *) sender 
{ 
    // Code never gets heree 
} 

if(_aButton ==`nil)是需要的,因爲單元格被重用。

現在該如何完成這項工作?謝謝。

+0

究竟是什麼錯誤?零檢查與重用無關,除非您將按鈕移到其他地方。 – Wain

+1

爲什麼不使用故事板for collectionview與原型單元格?更好的方式來設置故事板上的按鈕。 – merge

+0

框架設置正確,並在//中添加所有aButton的東西 – cdub

回答

0

在按鈕添加到視圖之前添加按鈕操作代碼....可能會有效。

// Call to button pressed for button 

[_aButton addTarget:self action:@selector(aButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 

// Add in all _aButton info here 

[self.contentView addSubview:_aButton]; 
+0

不知道爲什麼,但該開關允許按鈕被調用。 – cdub

0

我想,你初始化按鈕的方式會讓你的幀爲0,0,0,0。所以首先給它一個適當的框架和標題,以便在屏幕上可見。

然後嘗試點擊該標題,看看它是否有效。

0

目前還不清楚你想在這裏實現什麼,但按鈕不起作用,因爲你沒有設置它在單元格上的位置和大小。這可以通過設置框架或佈局約束來完成。

嘗試設置按鈕框:

_aButton.frame = CGRectMake(0.0f, 0.0f, 50.0f, 50.0f); 

您還可以設置背景顏色按鈕,只是爲了它的細胞可見:

_aButton.backgroundColor = [UIColor redColor]; 

一切是正確的,按鈕應工作。

相關問題