【问题标题】:adding functionality to programmatically created UIButtons向以编程方式创建的 UIButton 添加功能
【发布时间】: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 类型的未捕获异常终止'
  • 我相信这意味着按下的按钮没有任何功能。
  • 菲利普你能告诉我你的意思吗?我不熟悉这种功能

标签: ios swift uibutton


【解决方案1】:

看起来你正在使用UIKit框架,所以你可以使用.isHidden方法或.isEnabled

具有隐藏按钮的隐藏方法和启用方法将显示按钮,但用户将无法按下按钮。

要使用该方法,请编写以下代码。

Button.isHidden = true

或者

Button.is enabled = false

但是如果你使用这些方法,你需要有一个按钮,它会做相反的事情(如果它是 false,则将其设置为 true,如果它是 true,则将其设置为 false),以便可以再次使用该按钮。

【讨论】:

    【解决方案2】:

    尝试替换以下行: 函数名必须存在于 Selector 属性中

    SongButton.addTarget(self,action: #selector(self.SongButtonPressed(_:)), for: UIControlEvents.touchUpInside)

    而且最重要的函数 SongButtonPressed 必须在 viewDidLoad 之外

    【讨论】:

    • 在该行抛出一个错误,说“无法将类型 '(UIbutton) -> ()' 的值转换为预期的参数类型 'String'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多