swift 3中未解析的标识符

时间:2017-02-14 20:29:52

标签: uibutton swift3

我的代码正在尝试下载一些JSON数据并将其保存到数组中,然后遍历数组并为每个项创建一个按钮。我无法将功能分配给按钮以便为其提供功能。这是我的代码:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    //connect to website
    let SongArray: Array<Any>
    let url = URL(string:"*******")
    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(songButtonPressed(_:)), for: UIControlEvents.touchUpInside)  //button press / response

                        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!!")
}
 }

我在使用SongButton.addTarget ...

的行上收到错误

错误表示&#39;使用未解析的标识符&#34; SongButtonPressed&#34;&#39;即使它在viewDidLoad函数之后声明。

1 个答案:

答案 0 :(得分:0)

因为你声明了选择器SongButtonPressed(_:)(注意下划线)

func SongButtonPressed(_ sender: UIButton) { // no implicit unwrapped optional !!

顺便说一下,正确的选择器语法是#selector(SongButtonPressed(_:))

两个注释:

  • .mutableContainers对Swift没有任何影响。省略参数。并删除行let SongArray: Array<Any>。您应该收到 unused 警告。
  • 函数,方法和变量应该以小写字母开头。