【问题标题】:Button not clickable after adding as a subview to a UIView添加为 UIView 的子视图后,按钮不可点击
【发布时间】:2011-10-25 23:17:13
【问题描述】:

我创建了一个名为UICustomButton 的类,它是UIView 的子类。我将UIButton 添加到UIView 作为subview,如下面的代码所示:

-(id)initWithButtonType:(NSString *)type
{
    self = [super init];
    if (self) 
    {
        self.customButton = [self setupButtonWithTitle:type andFrame:frame];
        [self addSubview:self.customButton];
        self.customButton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];

    }
    return self;
}

我面临的问题是,虽然按钮出现了,但它们不可点击。我将按钮添加到UIView 的方式有问题吗?

编辑:补充一下,我将这个自定义按钮类实例用于单元格:

UICustomButton *customButton = [[UICustomButton alloc]initWithFrame:someFrame];
[cell.contentView addSubView:customButton];

【问题讨论】:

标签: objective-c ios uiview uibutton


【解决方案1】:

检查UICustomButton 对象的框架,如果self.customButton 超出其superView

【讨论】:

  • 是的,我的超级视图没有正确设置。那是造成问题的原因。问题解决了。谢谢!
  • 你能告诉我如何检查 UIButton 的框架以及按钮是否超出了它的 superView 吗?
【解决方案2】:

确保子视图的框架在其父视图的框架内。我遇到了两次问题,两次都是子视图的框架不正确。

【讨论】:

    【解决方案3】:

    您应该检查所有属性userInteractionEnabled 是否都打开:

    1. 检查 UITableView 的属性,您的单元格在此视图中显示
    2. 检查UITableViewCell 的属性,您在其中将此视图添加为子视图
    3. 检查UICustomButton 的属性
    4. -(id)initWithButtonType:(NSString *)type 中检查customButton 的属性

    【讨论】:

      【解决方案4】:

      我的按钮不起作用,因为我有两个视图。如您所见,第一个视图的宽度和高度均为 0 像素。我已将此视图设置为与 view2 相同的大小,然后我的按钮是可点击的。

          UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(325, 346, 0, 0)];
          view1.alpha = 0.90;
      
          UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 450, 150)];
          [view2.layer setCornerRadius:10.0f];
          view2.backgroundColor = [UIColor whiteColor];
      
          UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
          [btn addTarget:self action:@selector(addClosedToCollection) forControlEvents:UIControlEventTouchUpInside];
          [btn setFrame:CGRectMake(30, 30, 300, 32)];
          [btn setTitle:@"i'm a button" forState:UIControlStateNormal];
      
          [view2 addSubview:btn];
          [view1 addSubview:view2];
      

      我希望我已经帮助了某人:)

      【讨论】:

        【解决方案5】:

        您的外部视图的高度可能为 0。添加约束使其与子视图的高度相同(或高于),或者使用足够大的框架创建它。

        【讨论】:

          【解决方案6】:

          试着把它放在 if 语句之后:

          self.isTouchEnabled = YES;
          

          【讨论】:

            猜你喜欢
            • 2018-06-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-11-13
            • 1970-01-01
            • 2018-06-16
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多