首页 文章

通过触摸Swift中的单元格来调用

提问于
浏览
-2

我使用Core Date保存姓名和电话号码我想通过触摸单元拨打电话这里是我的代码:import UIKit import CoreData

class ViewController:UIViewController {

@IBOutlet weak var tableView: UITableView!

var people = [Person]()

override func viewDidLoad() {
    super.viewDidLoad()

    let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()
    do {
      let people = try PersistenceService.context.fetch(fetchRequest)
        self.people = people
        self.tableView.reloadData()
    } catch {}

}

@IBAction func onPlusTapped() {
    let alert = UIAlertController(title: "Add Person", message: nil, preferredStyle: .alert)
    alert.addTextField { (textField) in
        textField.placeholder = "Name"
    }
    alert.addTextField { (textField) in
        textField.placeholder = "Phone number"
        textField.keyboardType = .numberPad
    }
    let action = UIAlertAction(title: "Post", style: .default) { (_) in
        let name = alert.textFields!.first!.text!
        let phoneNumber = alert.textFields!.last!.text!
        let person = Person(context: PersistenceService.context)
        person.name = name
        person.phoneNumber = phoneNumber
        PersistenceService.saveContext()
        self.people.append(person)
        self.tableView.reloadData()

    }
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
}

override var prefersStatusBarHidden:Bool }

扩展ViewController:UITableViewDataSource {func numberOfSections(在tableView:UITableView中) - > Int {return 1}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
    cell.textLabel?.text = people[indexPath.row].name
    cell.detailTextLabel?.text = people[indexPath.row].phoneNumber
    return cell
}

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == .delete) {
        people.remove(at: indexPath.item)
        tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    UIApplication.shared.openURL(NSURL(string: "tel://" + (people[indexPath.row].phoneNumber?.description)!)! as URL)
    print(people[indexPath.row].phoneNumber?.description)
}

}

2 回答

  • 0

    无需添加@IBAction,您可以使用UITableViewDelegate中的didSelectRow

  • 1

    如果你在 UITableViewCell 内有一个UIButton,你已经在 UITableView 内实现了 didSelectRowAt 使用IBActions

相关问题