【问题标题】:Multiple UIButtons only one can be selected - subclass in swift多个 UIButtons 只能选择一个 - swift中的子类
【发布时间】:2015-02-18 13:43:33
【问题描述】:

我编写了一个选择和取消选择按钮的子类。我已经把这个子类放在视图控制器的大约 5 个按钮上。

我想修改代码,以便如果用户选择一个然后选择另一个,则第一个会被取消选择。

我正在考虑使用按钮上的 .tag 来计算已选择的按钮,并在按下下一个按钮时删除选择。

代码如下:

谢谢

class ChangeColour: UIButton {

    var buttontagpressed: Int = 0
    var isChecked:Bool = false{
        didSet{
            if isChecked == true {

                self.backgroundColor = UIColor(red:0.27, green:0.29, blue:0.31, alpha:1.0)
                self.setTitleColor(UIColor.whiteColor(), forState: .Normal)
                buttontagpressed = self.tag
            }

            else

            {
                self.backgroundColor = UIColor(red:0.09, green:0.83, blue:0.56, alpha:1.0)
                self.setTitleColor(UIColor(red:0.24, green:0.24, blue:0.24, alpha:1.0), forState: .Normal)

            }
        }
    }

    override func awakeFromNib() {
        self.addTarget(self, action: "buttonselected:", forControlEvents: UIControlEvents.TouchUpInside)
        self.isChecked = false
    }

    func buttonselected (sender:UIButton) {
        buttontagpressed = self.tag
        if (sender == self)
        {

            if isChecked == true
            {

                isChecked = false
            }

            else

            {

                isChecked = true

            }
        }
    }

}

【问题讨论】:

  • 任何人都请帮我提出任何建议。因为我正在完成这项如此简单的任务。

标签: ios swift uibutton


【解决方案1】:

而不是使用标签(我认为这是一个非常丑陋的解决方案),我倾向于向您的类添加一个属性,该属性保留对先前选择的按钮的引用。这个解决方案会更加优雅 - 或者您可以使用 UINotificationCenter 向所有按钮广播消息以启动取消选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-28
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多