且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-30 14:47:28

您可能只需要在 RecordingView 上将 userInteractionEnabled 设置为 YES.

You may simply need to set userInteractionEnabled to YES on your RecordingView.

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

Another problem is that you are creating the RecordingView with a frame width of 130, but you are setting the X-axis origin of playButton to 185. This means playButton is entirely outside of the bounds of its superview. The default value for clipsToBounds is NO, so the button is drawn anyway. But touch events will never reach the button, because they are rejected when the system hit-tests the RecordingView.

这来自 UIView 类参考:

This is from the hitTest:withEvent: documentation in UIView Class Reference:

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

Points that lie outside the receiver’s bounds are never reported as hits, even if they actually lie within one of the receiver’s subviews. This can occur if the current view’s clipsToBounds property is set to NO and the affected subview extends beyond the view’s bounds.

您需要使 RecordingView 的框架变宽,或者将 playButton 移动到其超级视图的边界内.

You need to either make RecordingView's frame wider, or move playButton to be inside the bounds of its superview.