以编程方式添加带有按钮的视图

2024-01-06

我想以编程方式添加一个视图和一个按钮,如下所示。

问题是单击按钮时按钮没有反应。我的意思是它既不会突出显示也不会调用选择器。

原因是我想为录音(声音文件)实现一个列表行。列表行应该可以选择进行向下钻取,并有一个播放按钮。所以我得到了一个RecordingView子类化UIView它本身使用构造函数中的目标添加按钮。请参阅下面的代码。

如果有人有更好的方法来做到这一点,这也可能是一个解决方案。

@implementation MyViewController

- (IBAction) myAction { 
    RecordingView *recordingView = [[RecordingView alloc] initWithFrame:CGRectMake(30, 400, 130, 50)withTarget:self];
    [recordingView setUserInteractionEnabled:YES];
    [[self view] addSubview:recordingView];
}

@implementation RecordingView

- (id)initWithFrame:(CGRect)frame withTarget:(id) target
{
    self = [super initWithFrame:frame];

    UIButton *playButton = [[UIButton alloc] initWithFrame:CGRectMake(185, 5, 80, 40)];
    [playButton setTitle:@"Play" forState:UIControlStateNormal];
    [playButton setTitleColor:[UIColor darkTextColor]forState:UIControlStateNormal];
    // creating images here ...
    [playButton setBackgroundImage:imGray forState: UIControlStateNormal];
    [playButton setBackgroundImage:imRed forState: UIControlStateHighlighted];
    [playButton setEnabled:YES];
    [playButton setUserInteractionEnabled:YES];
    [playButton addTarget: target 
                   action: @selector(buttonClicked:) 
         forControlEvents: UIControlEventTouchDown];

    [self addSubview:playButton];

    return self;
}

当我以同样的方式直接在视图控制器 .m 文件中添加按钮时,按钮确实会在单击时做出反应。所以有一些关于RecordingView。我需要在这里做些什么不同的事情?

另外,有没有更好的方法来提供触摸事件的目标和选择器?


您可能只需要设置userInteractionEnabled to YES在你的RecordingView.

另一个问题是您正在创建RecordingView框架宽度为 130,但您将 X 轴原点设置为playButton到 185。这意味着playButton完全超出了其超级视图的范围。默认值为clipsToBounds is NO,所以无论如何都会绘制按钮。但是触摸事件永远不会到达按钮,因为当系统命中测试时它们会被拒绝RecordingView.

这是来自hitTest:withEvent:文档在UIView类参考 https://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/UIView/UIView.html#//apple_ref/doc/uid/TP40006816-CH3-BBCCAICB:

位于接收器边界之外的点永远不会被报告为命中,即使它们实际上位于接收器的子视图之一内。如果当前视图的clipsToBounds属性设置为NO并且受影响的子视图超出了视图的边界。

你需要要么做RecordingView的框架变宽,或移动playButton位于其超级视图的范围内。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

以编程方式添加带有按钮的视图 的相关文章

随机推荐