简体   繁体   English

在UICollectionViewCell中点击一个UIButton

[英]Having a UIButton be tapped in a UICollectionViewCell

I have a UICollectionView with its cells all laid out. 我有一个UICollectionView及其所有单元格都已布置。

I have this declared as a subview: 我将此声明为子视图:

@property (nonatomic, strong) UIButton *aButton;

I then have that declared in each cell like so: 然后,我在每个单元格中都声明了这样的内容:

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];

The button click method is like so: 按钮单击方法如下所示:

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

The if(_aButton == `nil) is needed since cells get reused. 由于需要重复使用单元格,因此需要if(_aButton ==`nil)。

How do I make this work now? 我现在该如何工作? Thanks. 谢谢。

Add button action code before button added to view.... May be it will work . 在将按钮添加到视图之前添加按钮操作代码。...可能会起作用。

 // Call to button pressed for button

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

// Add in all _aButton info here

[self.contentView addSubview:_aButton];

I think, the way you are initializing the button is going to give you frame as 0,0,0,0 . 我认为,初始化按钮的方式将为您提供框架为0,0,0,0。 So first give it a proper frame and title to be visible on the screen. 因此,首先给它一个适当的框架和标题,使其在屏幕上可见。

Then try tapping on that title and see if it works or not. 然后尝试点击该标题,看看它是否有效。

It's unclear what you trying to achieve here, but the button is not working because you not setting it's position and size on the cell. 目前尚不清楚您要在这里实现什么,但是该按钮不起作用,因为您未在单元格上设置它的位置和大小。 It could be done by setting frame or layout constraints. 可以通过设置框架或布局约束来完成。

Try to set button frame: 尝试设置按钮框:

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

You can also set background color for the button, just to make it visible on the cell: 您还可以设置按钮的背景色,只是使其在单元格上可见:

_aButton.backgroundColor = [UIColor redColor];

Everything else is correct, button should work. 其他所有内容都正确,按钮应该起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM