【问题标题】:Having a UIButton be tapped in a UICollectionViewCell在 UICollectionViewCell 中点击 UIButton
【发布时间】:2015-11-18 17:50:26
【问题描述】:

我有一个 UICollectionView,它的所有单元格都布置好了。

我已将此声明为子视图:

@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) 是必需的,因为单元格可以重复使用。

我现在如何进行这项工作?谢谢。

【问题讨论】:

  • 究竟出了什么问题?除非您在其他地方删除按钮,否则 nil 检查与重用无关。
  • 你为什么不使用storyboard作为collectionview和prototype cell呢?更好的方法是在storyboard上设置按钮。
  • 框架在 // add all aButton stuff here 中设置得很好且正确

标签: ios objective-c uibutton uicollectionview uicollectionviewcell


【解决方案1】:

目前尚不清楚您要在此处实现什么,但该按钮不起作用,因为您没有在单元格上设置它的位置和大小。可以通过设置框架或布局约束来完成。

尝试设置按钮框架:

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

您还可以为按钮设置背景颜色,以使其在单元格上可见:

_aButton.backgroundColor = [UIColor redColor];

其他一切都正确,按钮应该可以工作。

【讨论】:

    【解决方案2】:

    在按钮添加到视图之前添加按钮操作代码....可能会起作用。

     // Call to button pressed for button
    
    [_aButton addTarget:self action:@selector(aButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    
    // Add in all _aButton info here
    
    [self.contentView addSubview:_aButton];
    

    【讨论】:

    • 不知道为什么,但那个开关允许按下按钮被调用。
    【解决方案3】:

    我认为,您初始化按钮的方式将使您的框架为 0,0,0,0 。所以首先给它一个合适的框架和标题,让它在屏幕上可见。

    然后尝试点击该标题,看看它是否有效。

    【讨论】:

      猜你喜欢
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多