【发布时间】:2017-02-14 14:49:57
【问题描述】:
我正在尝试向动态创建的按钮添加功能。我以前创建过具有功能的按钮,但从未以编程方式创建过。这是我的代码。
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 函数运行,到目前为止,当我点击一个按钮时,应用程序只会崩溃,尽管它们看起来很好。如何使用函数为这些按钮动态添加功能
【问题讨论】:
-
崩溃是什么错误?
-
如果你想让
SongButtonPressed运行,使用它作为选择器。 -
'libc++abi.dylib: 以 NSException 类型的未捕获异常终止'
-
我相信这意味着按下的按钮没有任何功能。
-
菲利普你能告诉我你的意思吗?我不熟悉这种功能