添加为UIView的子视图后,按钮无法点击

4

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

setupButtonWithTitle:andFrame: 是做什么的?此外,您需要确保如果 initWithButtonType: 的代码引用了 self 来添加一个选择器 buttonPressed,那么 buttonPressed 方法确实在同一类中实现。 - user244343
重复的问题 https://dev59.com/7Ww15IYBdhLWcg3wVaQa - phatmann
6个回答

10

检查您的UICustomButton对象的框架,如果self.customButton超出了其superView范围。


是的,我的父视图没有被正确设置。这就导致了问题。问题已经解决。谢谢! - Zhen
9
请问您如何检查UIButton的框架,并确定该按钮是否超出其父视图? - thandasoru

2

确保子视图的框架在其父视图的框架内。我遇到了这个问题两次,两次都是由于子视图的框架错误造成的。


0
我的按钮不起作用是因为我在彼此之间有两个视图。第一个视图,正如你所看到的,宽度和高度都是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

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


0

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

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

-1

尝试在if语句后面加上这个:

self.isTouchEnabled = YES;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接