我想添加功能動態創建按鈕。我已經創建了功能按鈕,但從未編程過。這是我的代碼。添加功能,以編程方式創建的UIButtons
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(self.songButtonPressed(_:)), for: .touchUpInside)
DispatchQueue.main.async {
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!!")
}
}
我非常想要做的就是使用功能SongButtonPressed當任一按鈕被按下運行,到目前爲止,當我點擊一個按鈕,雖然他們出現就好了應用程序只是崩潰。如何使用函數替換下面一行將功能添加到這些按鈕動態
碰到什麼錯誤? – Carcigenicate
如果您希望'SongButtonPressed'運行,請將其用作選擇器。 –
'libC++ abi.dylib:終止於類型爲NSException的未捕獲異常' – xteetsx