ios - 无法从文本字段中获取字符串变量以传递给邮件按钮功能
问题描述
我有一个应用程序,允许用户输入他们的联系信息,并将邮件发送到我的电子邮件地址,其中包含他们放入文本字段的信息。一切似乎都正常,我可以发送带有所需文本的邮件,但是我似乎无法从文本字段中输入信息。请帮忙!我对此有点陌生:)
var name: String?
@IBOutlet weak var nameField: UITextField!
var contact: String?
@IBOutlet weak var contactField: UITextField!
var other: String = "nothing"
@IBOutlet weak var otherField: UITextField!
@IBAction func sendEmail(_ sender: Any) {
let name = nameField.text
let contact = contactField.text
if other == nil {
}else{
let other = otherField.text!
}
当我单击按钮时,它会拉出邮件应用程序,其中包含正文中的信息。这是代码:
func configureMailController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["email@gmail.com"])
mailComposerVC.setSubject("Contact information")
mailComposerVC.setMessageBody("Another Friend! \nMy name or business is: \(name) \nMy contact information is: \(contact) \nMy additional information includes: \(other)", isHTML: false)
return mailComposerVC
}
这是邮件应用程序正文中的输出(即使我在文本字段中写东西):
“另一个朋友!
我的名字或公司是:无
我的联系方式是:无
我的附加信息包括:没有”
编辑:
我已将我的sendMail
函数更改为仅包含插座名称:
func configureMailController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["danielgannage@gmail.com"])
mailComposerVC.setSubject("Staples Day")
mailComposerVC.setMessageBody("Another Friend! \nMy name or business is: \(nameField.text) \nMy contact information is: \(contactField.text) \nMy additional information includes: \(otherField.text)", isHTML: false)
return mailComposerVC
}
现在我的输出有文本字段信息:
“另一个朋友!
我的名字或公司是:可选(“我在文本字段中输入的任何内容”)
我的联系信息是:可选(“我在文本字段中输入的任何内容”)
我的附加信息包括:可选(“我在文本字段中输入的任何内容”)“
但是我如何摆脱:Optional("")
围绕我的字符串?
解决方案
学习如何处理可选变量是学习 Swift 的重要组成部分。有几种方法可以做你想做的事情。如果这些字段中的一些没有被回答,您可以使用 nil 合并运算符来设置默认值。例如:
let name = nameField.text ?? "unknown"
或者,如果没有答案就不好,您可以防止这种情况:
guard let contact = contactField.text else {
// display missing info error
return
}
这将结束函数,而不是调用电子邮件客户端。
推荐阅读
- uicollectionview - CollectionView 使用 NSDiffableDataSource 和 UICollectionViewFlowLayout
- django - 如何向 django 用户模型添加选择字段
- ssl - 无法将笔记本电脑用作智能手机的代理
- angular - aws-amplify js 到 Angular 应用程序有错误:未定义全局
- javascript - 如何为 noUislider.js 定义自定义动画?
- java - 异常 java.lang.NoClassDefFoundError JavaMail Tomcat v8.5
- jquery - 尝试为正则表达式模式(数字、文件类型、密码等)做 jquery 验证方法
- c++ - 在 Mac OS Catalina 中设置 --std=C++17 默认值
- android - 如何使用改造向 api 添加身份验证?
- angular - 如何从 takeWhile 条件发出效果错误?