如何在Swift中的UIAlertView中添加UITableView

3

我该如何在UIAlertView中动态添加UITableView?将UIAlertView的子视图添加到UITableView后,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()
}

我在这里没有添加 let alertView = UIAlertView()..但是我已经在我的代码中添加了..仍然不起作用。 - vignesh TN
你不能做这个。只需在你的项目中添加按钮即可。 - Lumialxk
3
首先,UIAlertView已自iOS 8起被弃用,因此您可能需要查看UIAlertController。其次,警报框不适用于包含自定义子视图(例如TableView)。请考虑以模态方式展示您的表格,因为警报框旨在允许用户从某些可用操作中进行选择。 - tebs1200
3个回答

3
要创建Swift中的UITableView,您需要按照以下步骤进行:
  1. 创建一个UITableViewController类。

  2. 使用必要的代码填充其delegates(例如行数,didSelect,cellForRowAtIndexPath等)。

  3. 现在在AlertViewController中调用它的一个实例。

  4. 将所需数据(如行数和内容数组)传递给TableView。

  5. 将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")

0

我认为你不能使用UIAlertView来实现这个,但是你可以创建一个小视图并以模态的方式呈现它,或者使用UIPopoverPresentationController之类的东西。


0
为了在应用程序的多个位置使用表格/图片或自定义按钮操作的警报类型行为,我创建了一个名为“通用弹出视图”的示例项目,其中包括所有这些示例。该项目不使用转换委托。
此项目还演示如何将自定义字体和颜色调整到您的应用程序主题。
在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)
        }

更多信息请见链接https://github.com/shruezee/GenericPopovers


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接