an extension that creates a custom dialog with custom interface and button. in swift

To create an extension that creates a custom dialog with custom interface and button in Swift, you can use the following code:

main.swift
extension UIViewController {
    
    func showCustomDialog(title: String, message: String, buttonText: String, buttonAction: @escaping () -> Void) {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        // add custom interface to alert controller
        let customView = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 100))
        customView.backgroundColor = .white
        alertController.view.addSubview(customView)
        
        // add custom button to alert controller
        let customButton = UIButton(frame: CGRect(x: 0, y: 0, width: 150, height: 50))
        customButton.setTitle(buttonText, for: .normal)
        customButton.backgroundColor = .blue
        customButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        customView.addSubview(customButton)
        
        // present the alert controller
        present(alertController, animated: true, completion: nil)
        
        // set the button action as a selector
        objc_setAssociatedObject(self, "buttonAction", buttonAction, .OBJC_ASSOCIATION_COPY_NONATOMIC)
    }
    
    @objc private func buttonTapped() {
        // retrieve the button action and call it
        if let buttonAction = objc_getAssociatedObject(self, "buttonAction") as? () -> Void {
            buttonAction()
        }
    }
    
}
1404 chars
34 lines

With this extension, you can call showCustomDialog on any view controller to present a custom dialog with a custom interface and button. You can customize the title, message, button text, and button action as parameters of the showCustomDialog method.

gistlibby LogSnag