我循环遍历一个字符串数组。我将索引0处的元素与页面上按下的按钮的标题进行比较(理想情况下)。但我得到一个未解决的标识符错误,这意味着我做错了什么。如何将循环中的元素与在页面上以编程方式创建的按钮的标题进行比较。这是我的代码!问题出在底部的函数,在for循环中的if语句中。我不知道怎么说'如果元素的这个索引位置也是按下按钮的标题'。
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
var songArray: [Array<String>] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//connect to website
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 JSON = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! [[String]]
print(JSON)
//Make buttons with JSON array
var buttonY: CGFloat = 20
for song in JSON {
self.songArray.append(song)
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: UIControlEvents.touchUpInside) //button press / response
self.view.addSubview(SongButton) // adds buttons to view
}
}
catch
{
}
}
}
}
task.resume()
print(songArray)
}
func songButtonPressed(_ sender:UIButton!) { // function for buttons
for song in songArray {
if "\(song[0])" == SongButton.titleLabel?.text {
let URL = NSURL(string: "\(song[1])")
let player = AVPlayer(url: URL! as URL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
}
}
}
}
我的思路是遍历数组数组,将索引位置0与页面上的所有按钮标题进行比较,如果匹配,则将索引位置2加到AV播放器中。感谢您对我的代码背后的逻辑提供任何帮助或建议,我是初学者,我知道这个级别的编程有点过头了
答案 0 :(得分:0)
最有可能
set number = $<
@ n = ($number % 2)
或者
for song in songArray {
// the string interpolation "\()" is redundant
if song[0] == sender.titleLabel?.text { ... }
if song[0] == sender.title { ... }
与操作方法无关。