【问题标题】:Create a custom UIAlertController [closed]创建一个自定义 UIAlertController [关闭]
【发布时间】:2020-11-06 11:15:25
【问题描述】:

目标:使用 UITextField 数据条目和两个按钮创建警报:“接受”和“取消”。

我知道 UIAlertViewController 不会被更改。

我试图制作一个 UIViewController 但在 VC 的视图填充包含成员警报/模式视图的整个屏幕时遇到问题。

最简单的方法就是制作一个 UIView 并从主机控制它。

我想要的只是将 *customizable* 对话框/警报显示为 *presented* UIViewController。通过自定义警报,我的意思是能够接受来自用户的数据。

我也很好奇这将如何通过 SwiftUI 完成。

【问题讨论】:

    标签: ios swift swiftui uikit uialertviewcontroller


    【解决方案1】:

    如果你考虑使用 UIKit,那么你可以像这样在 UIAlertController 中放置一个文本字段。

    let alertController = UIAlertController(title: "Text Entry", message: "", preferredStyle: .alert)
    
    // Add a textField to your controller, with a placeholder value & secure entry enabled
    alertController.addTextField { textField in
        textField.placeholder = "Enter Text"
        textField.isSecureTextEntry = true
        textField.textAlignment = .center
    }
    
    // A cancel action
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
        print("Canelled")
    }
    
    // This action handles your confirmation action
    let confirmAction = UIAlertAction(title: "Accept", style: .default) { _ in
        print("Current password value: \(alertController.textFields?.first?.text ?? "None")")
    }
    
    // Add the actions, the order here does not matter
    alertController.addAction(cancelAction)
    alertController.addAction(confirmAction)
    
    present(alertController, animated: true, completion: nil)
    

    如果它回答了你的问题,请告诉我。

    【讨论】:

    • 我会玩的。谢谢。
    • 看起来我无法添加 1) 属性字符串或 2) 带有或不带有消息的子视图。
    • 我不完全确定,但对于属性字符串请查看this,对于子视图请尝试this。让我知道它是否有效。
    【解决方案2】:
    extension UIViewController {
    
    func showAlertWithCancel(title: String, message: String, okAction: String, cancel: String, completion: ((Bool, String) -> Void)? = nil ) {
        let sb_main = UIStoryboard.init(name: "Main", bundle: nil)
        let vc: CustomNewAlertVC = sb_main.instanceVC()
        vc.modalPresentationStyle = .custom
        vc.modalTransitionStyle = .crossDissolve
        vc._ok = okAction
        vc._msg = message
        vc._title = title
        vc._cancel = cancel
        vc.delegate = { aa in
            completion?(aa)
        }
        DispatchQueue.main.async {
            self.present(vc, animated: true, completion: nil)
        }
     }
    }
    

    显示警报使用:self.showAlertWithCancel(title: "Test" ....

    【讨论】:

      猜你喜欢
      • 2012-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      • 1970-01-01
      相关资源
      最近更新 更多