简体   繁体   English

如何更改单击按钮的图像?

[英]How do I change the image of button on click?

I have a preset image of a button in a custom cell, and I want that image to change when the button is clicked.我在自定义单元格中有一个按钮的预设图像,我希望该图像在单击按钮时发生变化。 How would I do that?我该怎么做? I put a switch in the button, and it works.我在按钮上放了一个开关,它起作用了。 When it is clicked it will play a song, and when it is clicked again it will stop.单击它时会播放一首歌曲,再次单击时它将停止播放。 I just want the image to change.我只想改变图像。 How would I do that?我该怎么做? The name of the button is playbutton .按钮的名称是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

    }
}

You don't need to declare playButton globally您不需要全局声明 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
}

in your playmusic function you can add the following line at the beginning在您的播放音乐功能中,您可以在开头添加以下行

sender.selected = !sender.selected

It 's so easy.它是如此容易。 You can set image for uibutton with UIControlState ex:您可以使用 UIControlState ex 为 uibutton 设置图像:

self.btnPlay.setImage(playImage, forState: UIControlState.Normal)
self.btnPlay.setImage(pauseImage, forState: UIControlState.Selected)

And When you click it, you change state of btnPlay:当你点击它时,你会改变 btnPlay 的状态:

self.btnPlay.selected = !self.btnPlay.selected

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在单击时更改collectionviewcell或按钮的渐变? - How do I change the gradient of a collectionviewcell or button on click? 当我单击完成按钮时,如何更改个人资料图片图像,该图像将在第一视图中更改? - How to change my profile picture image when I click on done button the image will be change in first view? 如何在按钮点击时立即更改UINavigationBar图像? - How to change UINavigationBar Image immediately on button click? 单击按钮如何更改imageView中的图像 - how to change image in imageView on button click 如何在单击按钮时更改tabbaritem图像? - How to change tabbaritem image on a button click? 按下按钮时如何更改图像? - How do I change an Image when a button is pressed? 如何点击时更改按钮的图像 - Swift - How do I change the image of a button when tapped - Swift 如何更改iOS按钮的图像和文本? - How do I change both the image and text of an iOS button? 如何为单击按钮时以编程方式创建的 UIImageView 设置动画? (每个按钮单击都会创建一个具有相同图像的新 UIImageView) - How do I animate a UIImageView that was created programatically upon button click? (Each button click creates a new UIImageView with the same image) 如何在单击时更改 TableView 标题按钮图像。 需要Objective c中的代码 - How Can I Change TableView Header Button Image On Click. Need code in Objective c
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM