如何在表视图中添加警报措施Cell& .xib(swift 3)

时间:2017-06-16 07:55:49

标签: ios swift uitableview tableviewcell uialertaction

我是快速世界的超级初学者。

我在Main.Storyboard中使用UITableView,在.xib文件中,我使用UITableViewCell

以下是ViewController.swift中的一些代码,与UITableView相关:

@IBOutlet weak var friendsTableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    friendsTableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return contacts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell : TableViewCell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
    let entry = contacts[(indexPath as NSIndexPath).row]

    cell.configureWithContactEntry(entry)
    cell.layoutIfNeeded()

    return cell
}

这是TableViewCell.swift中与TableViewCell.xib相关的代码。

@IBOutlet weak var contactNameLabel: UILabel!
@IBOutlet weak var contactPhoneLabel: UILabel!

    override func layoutIfNeeded() {
    super.layoutIfNeeded()
}

func configureWithContactEntry(_ contact: ContactEntry) {
    contactNameLabel.text = contact.name
    contactPhoneLabel.text = contact.phone ?? ""

}

而且,在TableViewCell.xib中,我使用UITableViewCell,2 Labels。

在这种情况下, 当我按下其中一个表格单元格时,如何添加AlertAction?

1 个答案:

答案 0 :(得分:0)

您必须将alertViewController添加到TableViewController而不是单元格本身。 但是,当您希望在用户触摸单元格时显示警报视图,只需实现tableViewDidselectRow并从那里显示您的alertView

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let alert = UIAlertController(title: "Alert", message: "This is an Alert", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
    present(alert, animated: true, completion: nil)
}

现在通过触摸一个单元格,它将显示警告