将文本从UITextField发送到swift中的短信

时间:2015-01-11 05:06:19

标签: swift ios8 uitextfield

我有一个UITextField,用户在其中输入一些文本。我希望在按下发送按钮时将该文本作为短信发送。我写的代码给了我一些问题。这是我到目前为止所做的。

import UIKit
import MessageUI

class ViewController: UIViewController,  MFMessageComposeViewControllerDelegate {



@IBOutlet weak var message: UITextField!


override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}


func canSendText() -> Bool {
    return MFMessageComposeViewController.canSendText()
}


func configuredMessageComposeViewController() -> MFMessageComposeViewController {

    let messageComposeVC = MFMessageComposeViewController()

    messageComposeVC.messageComposeDelegate = self
    messageComposeVC.body = message.text // This line doesn't work.
    return messageComposeVC
}


func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
    controller.dismissViewControllerAnimated(true, completion: nil)
}



@IBAction func sendtext(sender: AnyObject) {

    let messageComposer = ViewController()

        // Make sure the device can send text messages
        if (self.canSendText()) {
            // Obtain a configured MFMessageComposeViewController
            let messageComposeVC = messageComposer.configuredMessageComposeViewController()


            var vc = self.view?.window?.rootViewController

            vc?.presentViewController(messageComposeVC, animated: true, completion: nil)



        } else {
            // Let the user know if his/her device isn't able to send text messages
            let errorAlert = UIAlertView(title: "Cannot Send Text Message", message: "Your device is not able to send text messages.", delegate: self, cancelButtonTitle: "OK")
            errorAlert.show()
        }




}


}

有没有办法复制UITextField的所有内容并粘贴到messageComposeVC.body中?任何帮助表示赞赏。谢谢!

1 个答案:

答案 0 :(得分:1)

尝试更改行

let messageComposeVC = messageComposer.configuredMessageComposeViewController()

let messageComposeVC = self.configuredMessageComposeViewController()

messageComposerViewController的新实例,它没有设置消息。您正在第

行中创建ViewController的新实例
var messageComposer = ViewController()

这是message textField的新实例,不包含您输入的文字。