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

时间:2017-10-15 09:16:30

标签: ios swift core-data tableview call

我使用Core Date来保存姓名和电话号码 我想通过触摸细胞来打电话 这是我的代码: 导入UIKit 导入CoreData

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

覆盖var prefersStatusBarHidden:Bool {         返回true     } }

扩展名ViewController:UITableViewDataSource {     func numberOfSections(在tableView:UITableView中) - &gt; Int {         返回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 :(得分:1)

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

答案 1 :(得分:0)

如果您在didSelectRowAt

内有UIButton,则您已在UITableView内部实施UITableViewCell使用IBActions