У меня есть предустановленное изображение кнопки в пользовательской ячейке, и я хочу, чтобы это изображение изменилось при нажатии кнопки. Как мне это сделать? Я положил переключатель в кнопку, и он работает. Когда он будет нажат, он будет воспроизводить песню, а когда ее снова щелкнуть, она остановится. Я просто хочу, чтобы изображение изменилось. Как мне это сделать? Название кнопки - playbutton
.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = friendstable.dequeueReusableCellWithIdentifier("friendcell", forIndexPath: indexPath) as! FriendsMusicCell
cell.playbutton.tag = indexPath.row
cell.playbutton.addTarget(self, action: "playmusic:", forControlEvents: .TouchUpInside)
cell.customtitle.text = titleofsong[indexPath.row]
cell.customartist.text = artist[indexPath.row]
cell.customtitle.font = UIFont(name: "Lombok", size: 22)
cell.customtitle.textColor = UIColorFromRGB("4A90E2")
cell.customartist.font = UIFont(name: "Lombok", size: 16)
cell.customartist.textColor = UIColor.blackColor()
cell.customtitle.numberOfLines = 0;
cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
cell.backgroundColor = UIColor.clearColor()
return cell
}
func playmusic(sender: UIButton!) {
let playButtonrow = sender.tag
print(titleofsong[playButtonrow])
switch(buttonState){
case 0:
let searchTerm: String = titleofsong[playButtonrow]
let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=music"
let url: NSURL = NSURL(string: urlPath)!
print("Search iTunes API at URL \(url)")
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) -> Void in
do {
if let dict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
{
let previewUrl = NSURL(string: (dict["results"]![0]["previewUrl"] as? String)!)!
print(previewUrl)
self.player = AVPlayer(URL: previewUrl)
self.player.rate = 1.0
self.player.play()
}
} catch let jsonError as NSError {
}
}
task.resume()
}
buttonState = 1;
break;
case 1:
player.pause()
buttonState = 0;
default: break
}
}
Вам не нужно объявлять playButton глобально
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = friendstable.dequeueReusableCellWithIdentifier("friendcell", forIndexPath: indexPath) as! FriendsMusicCell
cell.playbutton.tag = indexPath.row
cell.playButton.setImage(playImage, forState: UIControlState.Normal)
cell.playButton.setImage(pauseImage, forState: UIControlState.Selected)
cell.playbutton.addTarget(self, action: "playmusic:", forControlEvents: .TouchUpInside)
cell.customtitle.text = titleofsong[indexPath.row]
cell.customartist.text = artist[indexPath.row]
cell.customtitle.font = UIFont(name: "Lombok", size: 22)
cell.customtitle.textColor = UIColorFromRGB("4A90E2")
cell.customartist.font = UIFont(name: "Lombok", size: 16)
cell.customartist.textColor = UIColor.blackColor()
cell.customtitle.numberOfLines = 0;
cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
cell.backgroundColor = UIColor.clearColor()
return cell
}
в вашей функции playmusic вы можете добавить следующую строку в начале
sender.selected = !sender.selected
Это так просто. Вы можете установить изображение для uibutton с помощью UIControlState ex:
self.btnPlay.setImage(playImage, forState: UIControlState.Normal)
self.btnPlay.setImage(pauseImage, forState: UIControlState.Selected)
И когда вы нажимаете на нее, вы меняете состояние btnPlay:
self.btnPlay.selected = !self.btnPlay.selected
playbutton
в функции tableView, и я хочу изменить изображение playbutton
в функции playmusic, и я не могу получить доступ к кнопке воспроизведения в функции.