首页 > 解决方案 > 无法从文本字段中获取字符串变量以传递给邮件按钮功能

问题描述

我有一个应用程序,允许用户输入他们的联系信息,并将邮件发送到我的电子邮件地址,其中包含他们放入文本字​​段的信息。一切似乎都正常,我可以发送带有所需文本的邮件,但是我似乎无法从文本字段中输入信息。请帮忙!我对此有点陌生:)

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("")围绕我的字符串?

标签: iosswiftstringbuttontextfield

解决方案


学习如何处理可选变量是学习 Swift 的重要组成部分。有几种方法可以做你想做的事情。如果这些字段中的一些没有被回答,您可以使用 nil 合并运算符来设置默认值。例如:

let name = nameField.text ?? "unknown"

或者,如果没有答案就不好,您可以防止这种情况:

guard let contact = contactField.text else { 
    // display missing info error 
    return
}

这将结束函数,而不是调用电子邮件客户端。


推荐阅读