presentViewController在Swift中不起作用

Dan*_*ons 2 ios presentviewcontroller swift xcode6

谢谢您阅读此篇.我想有一个函数Swift文件,我把我的项目的所有函数放入其中,其他Swift文件可以调用.我试图在函数文件中创建一个警报函数,当我传入一个特定的字符串时,它会显示一个特定的警报.当它在主文件中时它正在工作,但当我将它移动到函数文件时,presentViewController给我一个错误,说"使用未解析的标识符'presentViewController'." 请帮忙!这是我的代码:在函数文件中:

import Foundation
import UIKit

/**********************************************
Variables
***********************************************/
var canTapButton: Bool = false
var tappedAmount = 0

/**********************************************
Functions
***********************************************/

//the alert to ask the user to assess their speed
func showAlert(alert: String) -> Void
{
if(alert == "pleaseAssessAlert")
{
    let pleaseAssessAlert = UIAlertController(title: "Welcome!", message: "If this is your firs time, I encourage you to use the Speed Assessment Tool (located in the menu) to figure which of you fingers is fastest!", preferredStyle: .Alert)
    //ok button
    let okButtonOnAlertAction = UIAlertAction(title: "Done", style: .Default)
        { (action) -> Void in
            //what happens when "ok" is pressed
    }
    pleaseAssessAlert.addAction(okButtonOnAlertAction)

    presentViewController(pleaseAssessAlert, animated: true, completion: nil)
}
else
{
    println("Error calling the alert function.")
}    
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Mid*_* MP 5

presentViewControllerUIViewController类的实例方法.所以你不能像这样在你的函数文件上访问它.

你应该改变这样的功能:

func showAlert(alert : String, viewController : UIViewController) -> Void
{
   if(alert == "pleaseAssessAlert")
   {
       let pleaseAssessAlert = UIAlertController(title: "Welcome!", message: "If this is your firs time, I encourage you to use the Speed Assessment Tool (located in the menu) to figure which of you fingers is fastest!", preferredStyle: .Alert)
       //ok button
       let okButtonOnAlertAction = UIAlertAction(title: "Done", style: .Default)
       { (action) -> Void in
            //what happens when "ok" is pressed
       }
       pleaseAssessAlert.addAction(okButtonOnAlertAction)
       viewController.presentViewController(pleaseAssessAlert, animated: true, completion: nil)
   }
   else
   {
       println("Error calling the alert function.")
   }    
}
Run Code Online (Sandbox Code Playgroud)

在这里,您将一个UIViewController实例传递给此函数并调用该presentViewControllerView Controller类.


Arn*_*len 5

在Swift 3中:

该方法presentViewController被替换为present.

您可以像旧的一样使用它:

self.present(viewControllerToPresent, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)