通过构建我的第一个应用程序磕磕绊绊。尝试将变量从一个视图控制器(" ViewController")传递到另一个(" SecondViewController)。我在Stack Overflow上找到了一些代码,但是我收到了一个错误,并且不确定我做错了什么。在第一个视图控制器中,我有:
func prepareForSegue(segue: UIStoryboardSegue!, sender: Any!) {
if (segue.identifier == "segueTest") {
//Checking identifier is crucial as there might be multiple
// segues attached to same view
var secondVC = segue!.SecondViewController as ViewController;
secondVC.toPass = "email"
}
}
在第二个视图控制器中,我有:
var toPass:String!
我在第一个视图控制器中遇到错误: '类型的价值没有会员' (见图)
我为什么会这样沮丧。如果有任何建议,我将不胜感激。2
(Swift 3?)我发布了下面两个视图控制器的所有代码,看看是否有帮助。我为代码的混乱道歉。这是第一个视图控制器代码:
import UIKit
import FBSDKLoginKit
extension UserDefaults {
// check for is first launch - only true on first invocation after app install and sends user to answer questions
static func isFirstLaunch() -> Bool {
let hasBeenLaunchedBeforeFlag = "hasBeenLaunchedBeforeFlag"
let isFirstLaunch = !UserDefaults.standard.bool(forKey: hasBeenLaunchedBeforeFlag)
if (isFirstLaunch) {
UserDefaults.standard.set(true, forKey: hasBeenLaunchedBeforeFlag)
UserDefaults.standard.synchronize()
}
print(hasBeenLaunchedBeforeFlag)
return isFirstLaunch
}
}
class ViewController: UIViewController, FBSDKLoginButtonDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let loginButton = FBSDKLoginButton()
view.addSubview(loginButton)
loginButton.frame = CGRect(x: 16, y: 350, width: view.frame.width - 32, height: 50)
loginButton.delegate = self
self.view.backgroundColor = UIColor(patternImage: UIImage(named:"Book Funnel")!)
}
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
print("Did log out of Facebook")
}
//Gather Facebook demographic information
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
if error != nil {
print(error)
return
}
let login: FBSDKLoginManager = FBSDKLoginManager()
// Make login and request permissions
login.logIn(withReadPermissions: ["email", "public_profile"], from: self, handler: {(result, error) -> Void in
if error != nil {
// Handle Error
NSLog("Process error")
} else if (result?.isCancelled)! {
// If process is cancel
NSLog("Cancelled")
}
else {
// Parameters for Graph Request
let parameters = ["fields": "email, name"]
FBSDKGraphRequest(graphPath: "me", parameters: parameters).start {(connetion, result, error) -> Void in
if error != nil {
NSLog(error.debugDescription)
return
}
// Result
print("Result: \(result)")
// Handle vars
if let result = result as? [String:String],
let email: String = result["email"],
let fbId: String = result["id"] {
print("Email: \(email)")
print("fbID: \(fbId)")
func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
if segue!.identifier == "segueTest" {
if let secondVC = segue!.SecondViewController as? ViewController {
secondVC.toPass = "email"
}
}
}
}
}
}
})
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
}
第二个视图控制器代码:
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
class SecondViewController: UIViewController {
@IBOutlet weak var sliderLabel: UILabel!
@IBOutlet weak var verticalSlider: UISlider!
{
didSet{
verticalSlider.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_2))
}
}
//Change label as slider moves
@IBAction func verticalSliderChanged(_ sender: UISlider) {
var currentValue = Double(sender.value);
sliderLabel.text = "\(currentValue)"
}
@IBOutlet weak var ratingSubmitted: UIButton!
@IBAction func checkmarkPressed(_ sender: Any) {
func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named:"Book Funnel")!)
}
}
@IBOutlet weak var checkmarkButton: UIButton!
@IBAction func checkmarkButtonPressed(_ sender: Any) {
let img:UIImageView = UIImageView(frame: CGRect(x: 30, y: 180, width: 250, height: 320))
let randomImage = arc4random()
if (randomImage % 3 == 0) {
img.image = UIImage(named: "hero.jpg")
} else if (randomImage % 3 == 1) {
img.image = UIImage(named: "hillary.jpg")
} else {
img.image = UIImage(named: "thistimeisdifferent.jpg")
}
// img.contentMode = UIViewContentMode.ScaleAspectFill
// img.backgroundColor = UIColor.redColor()
self.view.addSubview(img)
var toPass: String!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:0)
您对第二个视图控制器的强制转换是错误的,因此它不知道其中的变量toPass
。
尝试更改此内容:
var secondVC = segue!.SecondViewController as ViewController;
对此:
if let secondVC = segue.destination as? SecondViewController {
secondVC.toPass = "email"
}
答案 1 :(得分:0)
错误消息告诉您确切的错误:UIStoryboardSegue
没有名为SecondViewController
的属性。您想使用属性destinationViewController
。
示例Swift 2.3代码(未测试):
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
if segue!.identifier == "segueTest" {
if let secondVC = segue!.destinationViewController as? ViewController {
secondVC.toPass = "email"
}
}
}
如果目标视图控制器实际上名为SecondViewController
,则第三行应为:
if let secondVC = segue!.destinationViewController as? SecondViewController {
另外,您可能需要考虑转向Swift 3语法。
答案 2 :(得分:0)
再看看你的代码。 var toPass: String!
应该在任何函数之外,仍在您的班级内。
@IBAction func checkmarkButtonPressed(_ sender: Any) {
let img:UIImageView = UIImageView(frame: CGRect(x: 30, y: 180, width: 250, height: 320))
let randomImage = arc4random()
if (randomImage % 3 == 0) {
img.image = UIImage(named: "hero.jpg")
} else if (randomImage % 3 == 1) {
img.image = UIImage(named: "hillary.jpg")
} else {
img.image = UIImage(named: "thistimeisdifferent.jpg")
}
// img.contentMode = UIViewContentMode.ScaleAspectFill
// img.backgroundColor = UIColor.redColor()
self.view.addSubview(img)
var toPass: String!
}
将其更改为:
class SecondViewController: UIViewController {
@IBAction func checkmarkButtonPressed(_ sender: Any) {
// IBAction function stuff
}
var toPass: String!
}