以编程方式添加一个button的视图
我想像下面这样以编程方式添加一个视图和一个button。
问题在于button在点击时不起作用。 我的意思是既没有突出显示或调用select器。
原因是我想实现一个logging(声音文件)的列表行。 列表行应该是可选的下钻,并有一个播放button。 所以我得到了一个RecordingView
子类化UIView
,它自己从构造函数中添加一个使用目标的button。 看下面的代码。
如果有人有更好的方法来做到这一点,也可以解决。
@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; }
当我以同样的方式添加button时,直接在视图控制器.m文件中,button确实会对点击作出反应。 所以关于RecordingView
有一些东西。 我需要在这里做不同的事情?
另外,有没有更好的方法来提供触摸事件的目标和select器?
您可能只需在您的RecordingView
上将userInteractionEnabled
设置为YES
。
另一个问题是,你正在创build一个框架宽度为130的RecordingView
,但是你将playButton
的X轴原点playButton
为185.这意味着playButton
完全在它的超级视图范围之外。 clipsToBounds
的默认值是NO
,因此无论如何都是绘制button。 但触摸事件永远不会到达button,因为当系统碰撞testingRecordingView
时,它们被拒绝。
这是来自hitTest:withEvent:
UIView类参考文档:
位于接收方边界之外的点不会被报告为点击,即使它们实际上位于接收方的子视图之一内。 如果当前视图的
clipsToBounds
属性设置为NO
,并且受影响的子视图超出视图的边界,则会发生这种情况。
您需要将RecordingView
的框架变宽,或者将playButton
移动到其超视图的范围内。