Swift触摸在静态表视图中无法识别

时间:2017-03-20 20:15:24

标签: ios swift xcode tableview

我有一个带静态单元格的表视图。

我的第二部分有一个标题但没有行,在该部分下我有一个标签,按下时应该调用sendEmail()函数,该函数将在他们的设备上打开电子邮件应用程序。

我尝试过使用标签,文本视图,按钮,覆盖didSelectCellForRow函数,但都失败了。

我完全失去了不被认可的东西。

我已将print语句添加到我的touchesBegan函数中,但它们从不打印。

可能是什么问题?

import UIKit
import MessageUI

class InfoTVC: UITableViewController, MFMailComposeViewControllerDelegate{

let ownerEmail = "test@email.com"
@IBOutlet weak var contactLbl: UILabel!

// MARK: - View functions

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

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


// MARK: - IBOutlet methods

@IBAction func backBtn(_ sender: Any) {
    _ = navigationController?.popViewController(animated: true)
    dismiss(animated: true, completion: nil)
}


// MARK: - Email methods

// Open users email app on device
func sendEmail(){
    if MFMailComposeViewController.canSendMail() {
        let mail = MFMailComposeViewController()
        mail.mailComposeDelegate = self
        mail.setToRecipients([ownerEmail])
        mail.setMessageBody("<p>Hello I had the chance to use your app and </p>", isHTML: true)
        present(mail ,animated: true, completion: nil)
    }
    else{
        // Failure
        print("failed to open mail")
    }
}

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    controller.dismiss(animated: true, completion: nil)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch: AnyObject in touches {
        let location = touch.location(in: self.view)
        if contactLbl.frame.contains(location) {
            print("yes")
            sendEmail()
        }
        else{
            print("no")
        }
    }
}
}

1 个答案:

答案 0 :(得分:2)

尝试添加点击手势识别器而不是处理触摸

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.youLabelTapped(_:)))
yourLabel.addGestureRecognizer(tapGesture)

OR 或者:将目标直接添加到您的标签

yourLabel.addTarget(self, action: #selector(self.youLabelTapped(_:)), forControlEvents: .TouchUpInside)

你将被称为func:

func youLabelTapped(_ sender: UITapGestureRecognizer) {
    print("label tapped")
}

修改

要求:不要忘记启用用户互动:

yourLabel.isUserInteractionEnabled = true