swiftuiviewlayerzposition

Swift UIView zPosition issue, views overlap on other views


I am writing a calendar view, I added three other views to its super view, so the calendar view should be on the topper layer, it looks fine on the simulator

On simulator

but later on, I found that I can't click the button, then I checked the view hierarchy, found that the other three views overlap on the calendar, it is so weird as the 3d preview and view on the simulator are different

On Hierarchy Debugger

Here is the code of UI Part

func updateUI() {

    if calendarView != nil {

        self.view.addSubview(calendarView!)

        self.calendarView!.frame.origin = calendarViewPosition!
        self.calendarView!.layer.zPosition = 5
        self.calendarView!.layer.cornerRadius = self.setting.itemCardCornerRadius
        self.calendarView!.layer.masksToBounds = true
        self.calendarView!.setViewShadow()
        UIView.animate(withDuration: 0.8, delay: 0, options: .curveEaseOut, animations: {
            self.calendarView!.frame.origin.y += 50
        }) { _ in
            
            var newCalendarPageCordiateYDifference: CGFloat = 10
            var newCalendarPageSizeDifference: CGFloat = 20
            var zPosition: CGFloat = 4
            
            for _ in 1 ... 3 {
                let newCalendarPage = UIView()
            
                newCalendarPage.frame = CGRect(x: self.calendarView!.frame.origin.x + newCalendarPageSizeDifference / 2, y: self.calendarView!.frame.origin.y, width: self.calendarView!.frame.width - newCalendarPageSizeDifference, height: self.calendarView!.frame.height - newCalendarPageSizeDifference)
                newCalendarPage.backgroundColor = .white
                newCalendarPage.layer.zPosition = zPosition
                newCalendarPage.layer.cornerRadius = self.setting.itemCardCornerRadius
                newCalendarPage.setViewShadow()
                
                self.view.addSubview(newCalendarPage)
                
                UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {
                    newCalendarPage.frame.origin.y -= newCalendarPageCordiateYDifference
                })
                
                zPosition -= 1
                newCalendarPageCordiateYDifference += 10
                newCalendarPageSizeDifference += 50
            }
            
           
        }
    }
    
    
   
    

}

Solution

  • Remove self.view.addSubview(newCalendarPage) this from for loop and Add subview like this

    self.view.insertSubview(newCalendarPage, belowSubview: calendarView)
    

    Another way is to disable user interaction like newCalendarPage.isUserInteractionEnabled = false