繁体   English   中英

将子视图添加到UIView后,按钮无法单击

[英]Button not clickable after adding as a subview to a UIView

我创建了一个名为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];

检查UICustomButton对象的框架,以及self.customButton是否超出其superView

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

我的按钮无法正常工作,因为我有两个视图。 如您所见,第一个视图的宽度和高度为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];

我希望我能帮助别人:)

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

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

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

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

self.isTouchEnabled = YES;

暂无
暂无

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

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