在我正在撰写的应用程序中,我有一个名为“User”的字符串,用于存储游戏的用户名。当在Swift文件中的任何其他位置打印时,字符串的值将打印我设置的值,作为可选项。
如果我尝试将此字符串用作操作表操作的标题,则该字符串将自动设置为nil,我可以将其视为操作的标题,并在我要求打印时打印该字符串(用户) )。
如果有人能够解释为什么会发生这种情况,或者如何防止这种情况发生,那就太好了。我还在下面发布了我的Swift文件,谢谢。
import UIKit
class MainViewController: UIViewController {
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var firstView: UIView!
@IBOutlet weak var secondView: UIView!
var user:String!
var playerTwo:String!
var playerThree:String!
var playerFour:String!
var playerFive:String!
var playerSix:String!
var userCards = [String]()
override func viewDidLoad() {
super.viewDidLoad()
firstView?.isHidden = false
secondView?.isHidden = true
}
@IBAction func valueDidChange(_ sender: UISegmentedControl) {
switch segmentedControl.selectedSegmentIndex {
case 0:
firstView.isHidden = false
secondView.isHidden = true
case 1:
firstView.isHidden = true
secondView.isHidden = false
default:
break;
}
}
@IBAction func confirm(_ sender: UIButton) {
let alertController = UIAlertController(title: "Action Sheet", message: "What would you like to do?", preferredStyle: .actionSheet)
let userButton = UIAlertAction(title: user /* Here I have tried with putting both 'user', and "\(user)"*/, style: .default, handler: { (action) -> Void in
print("User button tapped")
})
let deleteButton = UIAlertAction(title: "Delete button test", style: .destructive, handler: { (action) -> Void in
print("Delete button tapped")
})
let cancelButton = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in
print("Cancel button tapped")
})
alertController.addAction(userButton)
alertController.addAction(deleteButton)
alertController.addAction(cancelButton)
self.present(alertController, animated: true, completion: nil)
}
}
该值直接从另一个文件中的代码传递到上面的文件中:
覆盖func prepare(对于segue:UIStoryboardSegue,sender:Any?){
if segue.identifier == "showMainController" {
let VC = segue.destination as! MainViewController
VC.user = self.user
if playerTwo != nil {
VC.playerTwo = self.playerTwo
}
if playerThree != nil {
VC.playerThree = self.playerThree
}
if playerFour != nil {
VC.playerFour = self.playerFour
}
if playerFive != nil {
VC.playerFive = self.playerFive
}
if playerSix != nil {
VC.playerSix = self.playerSix
}
}
}
但是,该值通过多个视图控制器传递,最初在此处设置:
if (meTextField.text?.isEmpty)! == false {
let p1 = meTextField.text!
initialPlayersDict["player1"] = "\(p1)"
if errLabelNotBlank {
errorLabel.text = ""
errLabelNotBlank = false
}
}