swift 如何在 UIAlertView 中添加 UITableView

How to add UITableView in a UIAlertView in swift

如何在 UIAlertView 中动态添加 UITableView。将UIAlertView的subView添加到UITableView后不显示

 override func viewDidLoad() {
    super.viewDidLoad()
    tableView.frame         =   CGRectMake(0, 50, 320, 200);
    tableView.delegate      =   self
    tableView.dataSource    =   self
    tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}

@IBAction func textFieldCliked(sender: AnyObject) {
    alertView.message = "table view"
    alertView.addButtonWithTitle("Ok")
    alertView.addSubview(tableView)
    alertView.show()
}

我不认为你可以用 UIAlertView 做到这一点,但你可以制作一个小视图并以模态方式呈现它或类似 UIPopoverPresentationController

要在 Swift 中创建一个 UITableView:

  1. 创建一个 UITableViewController class。

  2. 使用必要的代码填充其代表(行数、didSelect、cellForRowAtIndexPath 等)。

  3. 现在在AlertViewController.

  4. 中调用它的一个实例
  5. 将需要的数据传递给 TableView(例如行数和内容数组)。

  6. 将 TableView 实例添加到您的警报视图。

我的代码片段:

let alertController : UIAlertController = UIAlertController(title: "Select email ID", message: nil, preferredStyle: .Alert)
alertController.view.backgroundColor = UIColor.whiteColor()
alertController.view.layer.cornerRadius = 8.0

let contactNumVC = contactNumberTableViewController ()

contactNumVC.count = emailIDs.count

contactNumVC.numbersArray = emailIDs

contactNumVC.preferredContentSize = CGSizeMake(alertController.view.frame.width, (44 * CGFloat(emailIDs.count)))

alertController.setValue(contactNumVC, forKeyPath: "contentViewController")

为了在应用程序的多个位置使用带有 table/image 的警报类型行为或自定义按钮操作,我创建了一个包含所有这些示例的示例项目 Generic popover。这没有使用转换委托。 此项目还演示自定义字体和颜色以适应您的应用程序主题。

在 Storyboard 中创建自定义 tableview/imageview/buttons 并调用如下

if let vc = self.storyboard?.instantiateViewController(withIdentifier: "TableContentViewController") as? TableContentViewController{
            vc.modalPresentationStyle = .overCurrentContext
             vc.popOverDelegate = self
            self.present(vc, animated: false, completion: nil)
        }

更多信息在 link https://github.com/shruezee/GenericPopovers