2014-11-25 77 views
0

標題說明了一切。這裏是我的代碼:UIControlState.Selected的圖像不出現

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

要出現checkbox_active當你鬆開按鈕,你應該爲所按下的按鈕選擇=真。

所以,你的功能應該是這樣的:

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 
} 
+0

請原諒我的無知,我在SWIFT很新:d – magohamoth 2014-11-25 11:04:48

+0

@Magohamoth我不能肯定地說什麼你的第二個問題,因爲你的代碼沒有完全滿足調試的所有要求,但是如果你不想創建像查看那樣的複選框,那麼UIButton是最好的方法。 – Yuvrajsinh 2014-11-25 11:12:22

+0

好的,謝謝你,我會保留UIButton! – magohamoth 2014-11-26 10:55:29