不显示UIControlState.Selected的图像

时间:2014-11-25 10:49:02

标签: ios swift selected uicontrolstate

标题说明了一切。这是我的代码:

func createCheckBoxButton(xPos: CGFloat, yPos: CGFloat, tag: Int) -> UIButton {
    var checkBox = UIButton(frame: CGRect(x: xPos, y: yPos, width: checkBoxSize, height: checkBoxSize))
    checkBox.setBackgroundImage(UIImage(named: "checkbox_inactive"), forState: UIControlState.Normal)
    checkBox.setBackgroundImage(UIImage(named: "checkbox_pressed"), forState: UIControlState.Highlighted)
    checkBox.setBackgroundImage(UIImage(named: "checkbox_active"), forState: UIControlState.Selected)
    checkBox.tag = tag
    checkBox.contentMode = .ScaleAspectFit
    checkBox.addTarget(self, action: "processButton:", forControlEvents: UIControlEvents.TouchUpInside)
    return checkBox
}

按下我的按钮时有一个被调用的函数:

func processButton(sender: UIButton) {
    if (answerViewArray[sender.tag].backgroundColor == UIColor.whiteColor()) {
        answerViewArray[sender.tag].backgroundColor = myColor.pinky()
    } else {
        answerViewArray[sender.tag].backgroundColor = UIColor.whiteColor()
    }
    let tag = answerButtonsArray[sender.tag]
    answer.buttonPressed(tag)
}

当我启动应用时,checkbox_inactive图片就在那里。当我按下并按住它时,会出现checkbox_pressed图像。但是,当我发布点击时,checkbox_inactive会再次显示,而不是checkbox_active

我也试过UIImageView,这对我来说是最好的解决方案。我将我的复选框设置为UIImageView,在我的一般视图的顶部,我放置了一个不可见的视图,以便我可以随处点击。但是当我按下我看不见的视图时,UIImageView就会消失。

以下是代码:

func createCheckBoxButton(xPos: CGFloat, yPos: CGFloat) -> UIImageView {
    var checkBox = UIImageView(frame: CGRect(x: xPos, y: yPos, width: checkBoxSize, height: checkBoxSize))
    checkBox.image = UIImage(named: "checkbox_inactive")
    checkBox.contentMode = .ScaleAspectFit
    return checkBox
}

这是一个名为:

的函数
func processButton(sender: UIButton) {
    if (answerViewArray[sender.tag].backgroundColor == UIColor.whiteColor()) {
        answerViewArray[sender.tag].backgroundColor = myColor.pinky()
        checkBoxArray[sender.tag].image = UIImage(named: "checkbox-active")
    } else {
        answerViewArray[sender.tag].backgroundColor = UIColor.whiteColor()
        checkBoxArray[sender.tag].image = UIImage(named: "checkbox-inactive")
    }

    let tag = answerButtonsArray[sender.tag]

    answer.buttonPressed(tag)
}

1 个答案:

答案 0 :(得分:1)

要在释放按钮时显示checkbox_active,您应该为按下的按钮选择= true。

所以你的功能应该是:

func processButton(sender: UIButton) {
  // If button not selected
  if(sender.selected==false){
    sender.selected = true;
  }
  else{ // If button already selected
    sender.selected = false;
  }

  // Do your other stuff
}