iOS开发:容器视图内嵌入的子控制器按钮无法响应点击
Hey there, let's work through why those buttons in your child view controller aren't responding to taps—this is a super common gotcha when animating views that start off-screen, so let's break down the most likely fixes:
Double-check your view's frame/bounds after animation
Sometimes when you animate a view from off-screen, even if it looks visually correct, its actualframemight still be stuck off-screen (especially if you used aCGAffineTransforminstead of updating the frame directly). UIKit uses the frame to determine tap detection areas, so if the frame's still outside the screen, taps won't register.
Fix this by updating the frame explicitly in your animation's completion block:UIView.animate(withDuration: 0.3, animations: { // Move the child view to its final visible position self.childViewController.view.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 200) }, completion: { _ in // If you used a transform to move it, reset it here to avoid hit-testing issues self.childViewController.view.transform = .identity })Ensure user interaction isn't disabled
It's easy to accidentally toggleuserInteractionEnabledwhen setting up off-screen views, or even during animation. Make sure both the child view controller's main view AND the individual buttons haveuserInteractionEnabled = true. You can check this in Storyboard's Attributes Inspector for the buttons, or set it explicitly in code after the animation finishes.Confirm the view hierarchy is correct
If you're manually moving the child's view around instead of adjusting the container view, you might have pushed it behind another view (so taps are going to the view above it) or removed it from the view hierarchy entirely.
Quick fix: After animation, callself.view.bringSubviewToFront(self.childViewController.view)to ensure it's on top. You can also use Xcode's View Debugger (Debug > View Debugging > Capture View Hierarchy) to visually check where the child view sits in the stack.Fix Auto Layout constraint conflicts (if you're using constraints)
If you set up constraints to position the child view off-screen initially, but didn't update them properly during animation, UIKit might be overriding your manual frame changes behind the scenes. Instead of animating the frame directly, update your constraint constants and animate the layout:// Assume you have an IBOutlet for the child view's top constraint (starts at -200, off-screen) self.childTopConstraint.constant = 0 UIView.animate(withDuration: 0.3) { self.view.layoutIfNeeded() }This keeps the view's layout in sync with UIKit's system, so hit-testing works exactly where the view appears on screen.
内容的提问来源于stack exchange,提问作者Jorge

