我想添加功能动态创建按钮。我已经创建了功能按钮,但从未编程过。这是我的代码。添加功能,以编程方式创建的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