Search code examples
iosswiftuipopovercontrolleruialertcontrolleruiactionsheet

Swift iOS -How to connect method in UIPopoverBackgroundView Class to a PopoverController in a different class?


I'm using a PopoverController and I want to get rid of the background shadow. Apple says to subClass the UIPopoverBackgroundView and return false for override class var wantsDefaultContentAppearance: Bool { get }

https://developer.apple.com/documentation/uikit/uipopoverbackgroundview/1619357-wantsdefaultcontentappearance

I subclassed it and set the bool to false but the shadow still shows. How do I connect this subclass to the PopoverController that I'm using inside my Actionsheet in my LogoutClass?

UIPopoverBackgroundView subclass:

class PopoverBackgroundView: UIPopoverBackgroundView {

override class var wantsDefaultContentAppearance: Bool {
        get {
            return false
        }
    }
}

LogoutController:

class LogoutController:UIViewController{

fileprivate func logOff(){

let actionSheet = UIAlertController(title: nil, message: "Logging out?", preferredStyle: .actionSheet)

 let logout = UIAlertAction(title: "Log Out", style: .default){
            (action) in
//bla bla bla
}

actionSheet.addAction(logout)

if let popoverController = actionSheet.popoverPresentationController{
            popoverController.sourceView = view
            guard let window = UIApplication.shared.keyWindow else { return }
            window.backgroundColor = .clear
            popoverController.sourceRect = CGRect(x:window.bounds.midX, y:window.bounds.midY, width:0, height:0)
            popoverController.permittedArrowDirections = []

        }
present(actionSheet, animated: true, completion: nil)
}
}

Solution

  • You will have to set popoverBackgroundViewClass property of your UIPopoverPresentationController instance like so :

    Objective C :

    popoverController.popoverBackgroundViewClass = [PopoverBackgroundView class];
    

    Swift

    popoverController?.popoverBackgroundViewClass = PopoverBackgroundView.self
    

    As per Apple docs :

    The default value of this property is nil, which causes the presentation controller to use the default popover appearance. Setting this property to a value other than nil causes the presentation controller to use the specified class to draw the popover’s background content. The class you specify must be a subclass of UIPopoverBackgroundView .