我正在尝试实现 UITapGestureRecognizer,我的想法是在点击标签时我会弹出一个显示要调用电话的号码的窗口,它应该会弹出一个提示说调用或取消!!
我编写的代码在 3 到 4 个地方对我有用,但我被困在一个地方 在此屏幕中,我有一个带有原型(prototype)单元格分组类型的表格 View ,请查看此图片:
第三细胞
现在如果我正在点击 065668982 我有 canOpenURL: failed for URL: "telprompt://065668982"- 错误: "This app is not allowed to query for scheme telprompt" 这实际上适用于 iPhone 而不是模拟器,它可以正常工作。
第二单元格
如果我正在点击 065454858 我有 canOpenURL: failed for URL: "telprompt://065668982"- 错误: "不允许此应用查询方案 telprompt" 实际上可以在 iPhone 上运行,而不是在模拟器上运行,并且可以正常工作。
第一个单元格
但对于第一个它永远不会工作并以 fatal error 结束:在展开可选值时意外发现 nil
注意:我正在从 API 获取电话号码并将 View Controller 中的数据附加到 UITableViewCell。
我希望我说得有道理,如果我不清楚,请提前感谢您的帮助,请在下面评论
这是我的代码:
import UIKit
import Foundation
class XyzTableViewCell: UITableViewCell
{
@IBOutlet weak var phoneNumber: UILabel!
var touchContact : String = ""
var myCell: MyCellData! {
didSet {
self.updateUI()
}
}
func updateUI()
{
touchContact = vicarCell.phone_no
//Tap Gesture
tapGestureAddonView()
}
//MARK:- Tap to Call and Open Email
func tapGestureAddonView(){
let contacttap = UITapGestureRecognizer(target: self, action:("contactTapped"))
contacttap.numberOfTapsRequired = 1
phoneNumber!.userInteractionEnabled = true
phoneNumber!.addGestureRecognizer(contacttap)
}
func contactTapped() {
// do something cool here
print("contactTapped")
print(touchContact)
dispatch_async(dispatch_get_main_queue())
{
if UIApplication.sharedApplication().canOpenURL(NSURL(string: "telprompt://\(self.touchContact)")!){
UIApplication.sharedApplication().openURL(NSURL(string: "telprompt://\(self.touchContact)")!)
}
else{
//showAlert("Info",message: "Your device could not called" ,owner: self)
}
}
}
最佳答案
问题:1) 你应该只添加一次手势 2) 你应该检查 NSURL
是否为 nil。让我假设您使用 Storyboard并稍微改进您的代码
class XyzTableViewCell: UITableViewCell
{
@IBOutlet weak var phoneNumber: UILabel!
var touchContact : String = ""
var myCell: MyCellData! {didSet {self.updateUI()}}
func updateUI() {
touchContact = myCell.phone_no // did you mean myCell instead vicarCell?
}
override func awakeFromNib() {
super.awakeFromNib()
tapGestureAddonView()
}
func tapGestureAddonView(){
let contacttap = UITapGestureRecognizer(target: self, action: #selector(contactTapped))
contacttap.numberOfTapsRequired = 1
phoneNumber!.userInteractionEnabled = true
phoneNumber!.addGestureRecognizer(contacttap)
}
func contactTapped() {
print("contactTapped")
print(touchContact)
if touchContact.isEmpty {return}
guard let url = NSURL(string: "telprompt://\(touchContact)") else {
print("url string invalid")
return
}
dispatch_async(dispatch_get_main_queue())
{
if UIApplication.sharedApplication().canOpenURL(url){
UIApplication.sharedApplication().openURL(url)
} else{
//showAlert("Info",message: "Your device could not called" ,owner: self)
}
}
}
}
关于ios - 在点击 UILabel(手势识别器)时,在一个单元格的 tableview 原型(prototype)单元格中找到 nil 并且它在另外两个单元格中工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38092160/