Ios 正在尝试从swift中的应用发送电子邮件
我试图在myViewController上显示一个电子邮件弹出窗口,但我收到了错误消息 使用未解析的标识符“present” 在线 现在(作曲家,动画:真) 值得注意的是,按钮位于collectionView单元格中。如何修复此错误,以便在按下按钮时屏幕上显示电子邮件概览 这是我的密码Ios 正在尝试从swift中的应用发送电子邮件,ios,swift,Ios,Swift,我试图在myViewController上显示一个电子邮件弹出窗口,但我收到了错误消息 使用未解析的标识符“present” 在线 现在(作曲家,动画:真) 值得注意的是,按钮位于collectionView单元格中。如何修复此错误,以便在按下按钮时屏幕上显示电子邮件概览 这是我的密码 import MessageUI class MessagesViewCell: UICollectionViewCell, MFMailComposeViewControllerDelegate { @IB
import MessageUI
class MessagesViewCell: UICollectionViewCell, MFMailComposeViewControllerDelegate {
@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBAction func emailButtonTapped(_ sender: Any) {
showMailComposer()
}
func showMailComposer() {
guard MFMailComposeViewController.canSendMail() else {
return
}
let composer = MFMailComposeViewController()
composer.mailComposeDelegate = self
composer.setToRecipients(["email"])
composer.setSubject("")
composer.setMessageBody("", isHTML: false)
composer.present(composer, animated: true)
present(composer, animated: true)
}
}
extension MessagesViewController: MFMailComposeViewControllerDelegate {
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
if let _ = error {
controller.dismiss(animated: true)
}
switch result {
case .cancelled:
print("Cancelled")
case .failed:
print("Failed to send")
case .saved:
print("Saved")
case .sent:
print("Email Sent")
default:
break
}
controller.dismiss(animated: true)
}
}
解决此问题的最简单方法是将
UIViewController
的弱引用传递给UICollectionViewCell
。然后在弱引用传递的UIViewController
上调用present,而不是在UICollectionViewCell
的实例上调用它。以下是方法:
在cellForItem
方法中:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Identifier, for: indexPath) as! MessagesViewCell
cell.controller = self
//...
return cell
}
在消息iewcell
中:
class MessagesViewCell: UICollectionViewCell, MFMailComposeViewControllerDelegate {
weak var controller: UIViewController?
func showMailComposer() {
guard MFMailComposeViewController.canSendMail() else {
return
}
let composer = MFMailComposeViewController()
composer.mailComposeDelegate = self
composer.setToRecipients(["email"])
composer.setSubject("")
composer.setMessageBody("", isHTML: false)
composer.present(composer, animated: true)
controller?.present(composer, animated: true)
}
您需要从
UIViewController
的实例调用present
。单元格不能显示新的视图控制器。您可以使用委派将按钮点击事件传递回视图控制器。这是否回答了您的问题?