我正在尝试为动态创建的按钮添加功能。我以前创建过具有功能的按钮,但从未以编程方式创建过。这是我的代码。
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 在按下任何按钮时运行,到目前为止,当我单击按钮时应用程序崩溃,尽管它们看起来很好。我如何使用函数动态地向这些按钮添加功能
最佳答案
看起来你使用的是UIKit
框架,所以你可以使用.isHidden
方法或者.isEnabled
隐藏按钮的隐藏方法和启用方法将显示按钮,但用户将无法按下按钮。
要使用该方法,请编写以下代码。
Button.isHidden = true
或者
Button.is enabled = false
但是如果你使用这些方法,你需要有一个按钮,它会做相反的事情(如果它是 false 则设置它为 true,如果它是 true 则设置为 false)以便可以再次使用该按钮。
关于ios - 向以编程方式创建的 UIButton 添加功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42229163/