简体   繁体   中英

How to add Alert Action in Table view Cell & .xib (swift 3)

I'm super beginner in swift world.

I use UITableView in Main.Storyboard, and in .xib file, I use UITableViewCell

Here is some code in ViewController.swift, related with 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
}

Here is the code in TableViewCell.swift, related with 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 ?? ""

}

And, in TableViewCell.xib I use UITableViewCell, 2 Labels.

In this condition, How can i add AlertAction when I press one of my table cell?

You have to add your alertViewController to your TableViewController not the cell itself. But as you want the alert view to show once the user touches a cell just implement tableViewDidselectRow and present your alertView from there

 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)
}

now by touching a cell it will present an alert

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM