Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

could not cast value of type UIView to UIButton

Tags:

ios

swift

i have made the game tic tac toe in swift .. the game is completed i am stuck on the last bit that when the user presses the play again button i want to set all the buttons images back to nil so that the user can start playing the game again. i used the tag property to set it back to nil. i coded this :

for i = 0 ; i < 8 ; i++ {
  var button = view.viewWithTag[i] as! UIButton
  button.setImage(nil, forState:.normal)
}

but it gives error

could not cast value of type UIView to UIButton

like image 594
Shahzaib Qureshi Avatar asked Dec 11 '22 19:12

Shahzaib Qureshi


1 Answers

You need to check if the tag is configured right

   for var i = 0 ; i < 8 ; i++ {
        let subview = view.viewWithTag(i)
        if subview?.isKindOfClass(UIButton) == true{
            let button = subview as! UIButton
            button.setImage(nil, forState:UIControlState.Normal)
        }else{
            print("Tag \(i) is not configured right")
        }
    }

Also,like @Dharmbir Choudhary said

If you use tag to get button,do not start with 0,because default tag is 0 it is easy to mess up.

like image 150
Leo Avatar answered Dec 29 '22 01:12

Leo