2017-04-21 28 views
0

我一直在搜索最近兩天來解決此問題。那我有問題的代碼部分是:[say practiceLabelVar gets the value optional(Goldfish)]iOS標籤不會更新字符串值的文本,但打印字符串在Swift中正常工作

class PracticeTyping: UIViewController { 
    @IBOutlet weak var practiceLabel: UILabel! 

    var practiceLabelVar: String? 
    var x = "test" 

    override func viewDidLoad() { 
     super.viewDidLoad() 

    if let newPracticeLabelVar = practiceLabelVar { 

      self.practiceLabel.text = newPracticeLabelVar 

      print ("\(newPracticeLabelVar)") 

      x = newPracticeLabelVar 

     } else { 

      print ("\(x)") 

     }  
    } 
} 

我得到的輸出是在控制檯如下:

test 

Goldfish 

注:代碼打印在別的價值語句然後在if語句中打印代碼。

practiceLabel.text沒有改變並保持其默認值。

請幫忙。 感謝

+0

你在哪裏分配「金魚」練習標籤變量?這是因爲你沒有給練習變量變量賦予任何值。 – dRAGONAIR

+0

我在另一個視圖中從表視圖控制器分配值金魚。當我點擊一個按鈕@IBAction FUNC practiceTyping(_發件人:任意){ performSegue(withIdentifier: 「practiceTypingSegue」,發件人:個體經營) 讓PracticeTypingVar:PracticeTyping = self.storyboard .instantiateViewController(withIdentifier:「PracticeTypingView 「)as! PracticeTyping PracticeTypingVar.practiceLabelVar = myFavoriteAnimals [(發送者作爲AnyObject).TAG]。名稱 self.present(PracticeTypingVar,動畫:真,完成:無) } – Amr

回答

0

終於想通了。根據您在上面添加的評論,您從另一個角度設置「金魚」,如上所述,下面是代碼相同@IBAction func practiceTyping(_ sender: Any) { performSegue(withIdentifier: "practiceTypingSegue", sender: self) let PracticeTypingVar: PracticeTyping = self.storyboard?.instantiateViewController(withIdentifier: "PracticeTypingView") as! PracticeTyping PracticeTypingVar.practiceLabelVar = myFavoriteAnimals[(sender as AnyObject).tag].name self.present(PracticeTypingVar, animated: true, completion: nil) }

您在這裏做的是您正在展示「PracticeTyping」viewController 2次,one與performSegue()和其他與self.present(viewController)是錯誤的。之所以首先打印「測試」是因爲當您通過performSegue呈現視圖時,您沒有爲「practiceLabelVar」設置值。 所以刪除performSegue(withIdentifier: "practiceTypingSegue", sender: self),你很好走。

+0

非常感謝,它的工作。 – Amr

+0

歡迎您:) – dRAGONAIR

0

我想請你到好心明白什麼是Optional Chaining as an Alternative to Forced Unwrapping

的代碼運行良好,它只是檢查是否存在有或沒有價值,是的,有沒有價值,從而偏離航線的其他條件將被執行。嘗試分配一些值,你就會明白它是如何工作

注:有一個在var practiceLabelVar: String?沒有價值,如果有它一定的價值,如果再讓將工作,否則將執行

+0

爲practiceLabelVar的值來自tabelView和代碼打印我正在尋找正確的值。我現在的問題是在practiceLabel.text中獲取此值謝謝 – Amr