我有一个应用程序,允许用户输入他们的联系信息,并将其包含在文本字段中的信息发送到我的电子邮件地址。一切似乎都可以正常工作,我可以发送带有所需文本的邮件,但是似乎无法从文本字段中输入信息。请帮忙!我对此有点陌生:)
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(“无论我在文本字段中输入什么”)
我的联系信息是:可选(“我在文本字段中输入的内容”)
我的其他信息包括:可选(“我在文本字段中输入的所有内容”)
但是如何摆脱字符串周围的Optional("")
?
答案 0 :(得分:4)
学习如何处理可选变量是学习Swift的重要组成部分。有几种方法可以执行您要尝试执行的操作。如果可以解决某些字段,请使用nil合并运算符设置默认值。例如:
//other usings
using System.Data.SqlClient;
//other code
public async Task<bool> testCnxTimeout(SqlConnection cnx)
{
cnx.OpenAsync(); //this line produces the error
return true;
}
或者,如果没有答案也不行,那么您可以避免这种情况:
let name = nameField.text ?? "unknown"
这将结束功能,并且不调用电子邮件客户端。
答案 1 :(得分:-1)
只需添加!最后像 让contact = contactField.text!