-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函數。
我在做這樣的小改動之前更關注功能,根本不影響我的代碼。我在這篇文章中對你所說的所有修改進錯誤仍然存在於相同的地方。 – xteetsx
我看到了,使用'#selector(SongButtonPressed(_ :))'我更新了答案。 – vadian
我補充說,但錯誤仍然存在 – xteetsx