Swift: how to create a convenience init for UIAlertController with no parameters

420 views Asked by At

I am trying to create a convenience init with no parameters for a subclassed UIAlertController, but it is giving me an error.

It gives me this error:

Use of self in delegating initializer before self.init is called

class AvatarSelectionAlert: UIAlertController {

    convenience init(test: String) {
        let title = NSLocalizedString("ALERT_CHOOSE_AVATAR_TITLE", comment: "")
        let message = NSLocalizedString("ALERT_CHOOSE_AVATAR_MESSAGE", comment: "")
        self.init(title: title, message: message, preferredStyle: .ActionSheet)

        let selectPremadeAvatarAction = UIAlertAction(title: NSLocalizedString("SELECT_PREMADE_AVATAR", comment: ""), style: .Default) { Void in

        }
        addAction(selectPremadeAvatarAction)

        let chooseFromGalleryAction = UIAlertAction(title: NSLocalizedString("CHOOSE_FROM_GALLERY", comment: ""), style: .Default) { Void in

        }
        addAction(chooseFromGalleryAction)

        let takeNewPictureAction = UIAlertAction(title: NSLocalizedString("TAKE_NEW_PICTURE", comment: ""), style: .Default) { Void in

        }
        addAction(takeNewPictureAction)

        let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { Void in
        }
        addAction(cancelAction)
    }
}

I have also tried to call self.init() before calling the other self.init, but it crashes.

Is it possible to create a convenience init with no parameters?

2

There are 2 answers

0
Prabhu.Somasundaram On

what are you trying to achieve in subclassing UIAlertController?

Subclassing Notes

The UIAlertController class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.Refer here

0
JerryZhou On

Just do the extension of UIAlertController.

extension UIAlertController {

    public convenience init?(test: String) {
        let title = NSLocalizedString("ALERT_CHOOSE_AVATAR_TITLE", comment: "")
        let message = NSLocalizedString("ALERT_CHOOSE_AVATAR_MESSAGE", comment: "")
        self.init(title: title, message: message, preferredStyle: .actionSheet)

        let selectPremadeAvatarAction = UIAlertAction(title: NSLocalizedString("SELECT_PREMADE_AVATAR", comment: ""), style: .default) { Void in

        }
        addAction(selectPremadeAvatarAction)

        let chooseFromGalleryAction = UIAlertAction(title: NSLocalizedString("CHOOSE_FROM_GALLERY", comment: ""), style: .default) { Void in

        }
        addAction(chooseFromGalleryAction)

        let takeNewPictureAction = UIAlertAction(title: NSLocalizedString("TAKE_NEW_PICTURE", comment: ""), style: .default) { Void in

        }
        addAction(takeNewPictureAction)

        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { Void in
        }
        addAction(cancelAction)
    }

}