作为子视图添加到 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];
I have created a class called UICustomButton
, which is a subclass of UIView
. I added a UIButton
to UIView
as a subview
as shown in my code below:
-(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;
}
The problem I am facing is that although the button appears, they are not clickable. Is there something wrong with the way I am adding the buttons to the UIView
?
EDIT: To add on, I am using this custom button class instance to a cell:
UICustomButton *customButton = [[UICustomButton alloc]initWithFrame:someFrame];
[cell.contentView addSubView:customButton];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
检查
UICustomButton
对象的框架,以及self.customButton
是否超出其superView
范围。check the frame of your
UICustomButton
object, and ifself.customButton
is out of itssuperView
.确保子视图的框架位于其父视图的框架内。我遇到这个问题两次,两次子视图的框架都不正确。
Make sure that the frame of the subview is within the frame of its superview. I encountered the issue twice and both times the frame of the subview was incorrect.
您应该检查所有属性
userInteractionEnabled
是否已打开:UITableView
的属性UITableViewCell
的属性,其中您将此视图添加为子视图UICustomButton
的属性-(id)initWithButtonType:(NSString *)type
中customButton
的属性You should check if all properties
userInteractionEnabled
are on:UITableView
where your cells with this view are displayedUITableViewCell
where you add this view as subviewUICustomButton
customButton
in-(id)initWithButtonType:(NSString *)type
我的按钮不起作用,因为我彼此有两个视图。正如您所看到的,第一个视图的宽度和高度均为 0 像素。我已将此视图设置为与 view2 相同的大小,然后我的按钮可以单击。
我希望我已经帮助别人了:)
My button was not working because i had two views in each other. The first view, as you can see, has a width and heigth of 0 pixels. I've made this view the same size as view2 and then my button was clickable.
i hope i've helped somebody out :)
您的外部视图的高度可能为 0。添加约束,使其与子视图的高度相同(或更高),或者使用足够大的框架创建它。
Your outer view probably has a height of 0. Add constraints that makes it the same height as (or higher than) the subviews, or create it with a frame that is large enough.
尝试将其放在 if 语句之后:
try putting this after the if statement: