我试图从 Collection View 单元 Controller 发送邮件,但出现错误。这是完整的代码:
import Foundation
import UIKit
import MessageUI
import Parse
import Bolts
class CollectionViewCell: UICollectionViewCell, MFMailComposeViewControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var imageText: UILabel!
@IBOutlet weak var uploadedTimeLabel: UILabel!
@IBOutlet weak var currentUserLabel: UILabel!
@IBOutlet weak var flagContentButton: UIButton!
var deviceID = [String]()
var parseObject:PFObject?
@IBAction func buttonClick(sender: AnyObject) {
println(deviceID)
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.presentViewController(mailComposeViewController, animated: true, completion: nil)
} else {
self.showSendMailErrorAlert()
}
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property
mailComposerVC.setToRecipients(["test@email.com"])
mailComposerVC.setSubject("Test subject")
mailComposerVC.setMessageBody("Test mail!", isHTML: false)
return mailComposerVC
}
func showSendMailErrorAlert() {
let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
sendMailErrorAlert.show()
}
// MARK: MFMailComposeViewControllerDelegate
func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
}
错误行:
self.presentViewController(mailComposeViewController, animated: true, completion: nil)
错误代码:
'CollectionViewCell' does not have a member named 'presentViewController'
有什么建议吗?
最佳答案
您可以使用完成 block 或委托(delegate)来通知 View Controller ,如下所示。您可以在 cellForItemAtIndexPath
中的单元格上设置 delegate
或 notifyViewController
。这样,您可以告诉每个单元格您想要处理呈现邮件 Controller 的 Controller ,并且 Controller 可以决定如何执行此操作。
protocol CollectionViewCellDelegate {
func notifyViewController(mailViewController: MFMailComposeViewController)
}
class CollectionViewCell: ... {
//...
var delegate: CollectionViewCellDelegate?
// you could use this completion block property in place of a delegate
var notifyViewController: ((MFMailComposeViewController) -> Void)?
//...
@IBAction func buttonClick(sender: AnyObject) {
println(deviceID)
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
delegate?.notifyViewController(mailComposeViewController)
// OR
notifyViewController?(mailComposeViewController)
} else {
self.showSendMailErrorAlert()
}
}
//...
}
关于ios - 从 CollectionViewCell.swift 发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32953861/