Swift:ScrollView内按钮触发添加底部全屏子视图的异常问题
Hey there, let's work through your issue step by step! First, I notice you've already fixed the screen height problem using UIScreen.main.bounds—great start. The core issues now are related to where you're adding Subview3 and how you're handling its animation positioning.
问题核心分析
From your code and print results, two key issues are causing Subview3 not to display correctly:
- Wrong parent view for Subview3: You're adding Subview3 as a child of Subview2, which is inside a UIScrollView. This means all coordinates are relative to Subview2, and since UIScrollView defaults to
clipToBounds = true, any content outside Subview2's bounds gets cut off. - Misaligned animation logic: Your animation is adjusting the frame of a view inside Subview3 instead of Subview3's position relative to the screen.
解决方案
1. Add Subview3 to the correct parent view
You need to attach Subview3 to the top-level view of your screen, not Subview2's hierarchy. Here are two reliable ways:
- If Subview2 can access its parent ViewController (via delegate, closure, or direct reference):
// Inside Subview2's button tap handler if let parentVC = self.parentViewController { parentVC.view.addSubview(subview3) } - For iOS 13+, use the active key window (more reliable than the old
keyWindowmethod):if let window = UIApplication.shared.connectedScenes .filter({$0.activationState == .foregroundActive}) .compactMap({$0 as? UIWindowScene}) .first?.windows .first(where: {$0.isKeyWindow}) { window.addSubview(subview3) }
2. Fix Subview3's initial frame
Now that Subview3 is in the top-level view, set its initial position to sit just below the screen (ready to slide up):
let screenBounds = UIScreen.main.bounds // Calculate the desired height for Subview3 first let targetHeight = min(CGFloat(self.items.count) * self.itemHeight - 1, screenBounds.height) // Initial frame: off-screen at the bottom, full screen width subview3.frame = CGRect(x: 0, y: screenBounds.height, width: screenBounds.width, height: targetHeight) // Update the table height constraint upfront subview3.tableHeightConstraint?.constant = targetHeight
3. Adjust the animation logic
Modify the expandFromBottom() method to animate Subview3's own frame, sliding it up from the bottom:
func expandFromBottom() { let screenBounds = UIScreen.main.bounds let targetYPosition = screenBounds.height - (self.tableHeightConstraint?.constant ?? 0) UIView.animate(withDuration: 0.5) { self.frame.origin.y = targetYPosition } }
Bonus Optimization Tip
For a better user experience:
- Add a semi-transparent background overlay to Subview3, and allow tapping the overlay to dismiss the view.
- Consider using Auto Layout instead of frame-based layout for better device compatibility. You could pin Subview3 to the bottom, left, and right of the parent view, then animate the bottom constraint's constant to slide it up.
内容的提问来源于stack exchange,提问作者Priyanshu Goyal

