2017-02-14 87 views
-2

我的代碼試圖下載一些JSON數據並將其保存到數組,然後遍歷數組併爲每個項目創建一個按鈕。我無法將我的功能分配給按鈕以提供功能。這裏是我的代碼:swift 3中未解決的標識符

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

    //connect to website 
    let SongArray: Array<Any> 
    let url = URL(string:"*******") 
    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in 
     if error != nil 
     { 
      print("error") 
     } 
     else 
     { 
      if let content = data 
      { 
       do 
       { 
        //download JSON data from php page, display data 
        let SongArray = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! [[String]] 
        print(SongArray) 

        //Make buttons with JSON array 
        var buttonY: CGFloat = 20 
        for song in SongArray { 
         let SongButton = UIButton(frame: CGRect(x: 50, y: buttonY, width: 250, height: 30)) 
         buttonY = buttonY + 50 // 50px spacing 

         SongButton.layer.cornerRadius = 10 //Edge formatting for buttons 

         SongButton.backgroundColor = UIColor.darkGray //Color for buttons 

         SongButton.setTitle("\(song[0])", for: UIControlState.normal) //button title 

         SongButton.titleLabel?.text = "\(song[0])" 

         SongButton.addTarget(self,action: #selector(songButtonPressed(_:)), for: UIControlEvents.touchUpInside) //button press/response 

         self.view.addSubview(SongButton) // adds buttons to view 
        } 
       } 
       catch 
       { 

       } 
      } 
     } 
    } 
    task.resume() 

} 

} //close viewDidLoad 

func songButtonPressed(_sender:UIButton!) { // function for buttons 

if sender.titleLabel?.text == "\("Song[0]")" { 
    print("So far so good!!") 
} 
} 

我與SongButton.addTarget線得到一個錯誤......

錯誤說「未解決的標識符‘SongButtonPressed’的使用」,即使它的後右聲明viewDidLoad函數。

回答

0

既然你聲明的選擇SongButtonPressed(_:)它(注意下劃線)

func SongButtonPressed(_ sender: UIButton) { // no implicit unwrapped optional !! 

順便說一句正確的選擇語法是#selector(SongButtonPressed(_:))

有兩點需要注意:

  • .mutableContainers有沒有影響迅速。省略參數。並刪除行let SongArray: Array<Any>。你應該得到一個未使用的警告。
  • 函數,方法和變量應該以小寫字母開頭。
+0

我在做這樣的小改動之前更關注功能,根本不影響我的代碼。我在這篇文章中對你所說的所有修改進錯誤仍然存​​在於相同的地方。 – xteetsx

+0

我看到了,使用'#selector(SongButtonPressed(_ :))'我更新了答案。 – vadian

+0

我補充說,但錯誤仍然存​​在 – xteetsx

相關問題