使用相同图像切换多个UIButton的最佳方法

时间:2015-11-27 22:52:41

标签: swift checkbox uibutton

在我的应用程序中,我使用UIButton作为检查按钮。我有大约10个UIButton,它们都应该在两个Image之间切换。显示“x”的图像和显示复选标记的另一个图像。我为每个UIButton都有一个动作事件,但由于所有10个UIButton在两个图像之间切换,有没有办法以最好的方式实现这一点。现在我只知道这个解决方案,每个按钮都有一个布尔标志,当切换时我将标志设置为true或false。但对我来说,这似乎是一种不好的做法。

其中一个UIButton的示例:

var MenuBtnSelect = false
func GlutenSelect(sender: AnyObject)
{
    if(!MenuBtnSelect)
    {
        sender.setImage(UIImage(named: "CheckMark"), forState: .Normal)
        MenuBtnSelect = true
    }
    else
    {
        sender.setImage(UIImage(named: "NotCheckMark"), forState: .Normal)
        MenuBtnSelect = false

    }


}

2 个答案:

答案 0 :(得分:3)

首先,您必须为每个按钮设置NotCheckMark图像,然后您可以在没有布尔标志的情况下创建相同的图像。

@IBAction func pushAnyButton(sender: AnyObject) {
    if  let  btnImage : UIButton = sender as? UIButton {
        if (btnImage.currentImage == UIImage(named: "CheckMark"))
        {
            btnImage.setImage(UIImage(named: "NotCheckMark"), forState: .Normal)
        }
        else
        {
            btnImage.setImage(UIImage(named: "CheckMark"), forState: .Normal)
        }
    }
}

如果将此方法连接到按钮,则可以将此功能用于所有10个按钮。或者你可以这样更紧凑:

@IBOutlet weak var anyCheckBoxButton: UIButton!

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

    anyCheckBoxButton.setImage(UIImage(named: "CheckMark"), forState: .Selected )
    anyCheckBoxButton.setImage(UIImage(named: "NotCheckMark"), forState: .Normal )
}

@IBAction func pushAnyCheckBoxButton(sender: AnyObject) {
    anyCheckBoxButton.selected = !anyCheckBoxButton.selected
}

第二个想法来自here

答案 1 :(得分:0)

只需将每个按钮用作复选标记标记= 1000.如果sender.tag == 1000则关闭,将其设置为1001并更改图像。试试这样:

import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func switchImage(sender: UIButton) {
        sender.toggleSwitch
    }
}

extension UIButton {
    var toggleSwitch: Bool {
        if tag == 1000 {
            tag = 1001
            setImage(UIImage(named: "CheckMark"), forState: .Normal)
            return true
        } else {
            tag = 1000
            setImage(UIImage(named: "NotCheckMark"), forState: .Normal)
            return false
        }
    }
}