J. Doe
J. Doe

Reputation: 13033

Subclassing a UIButton programmatically?

I have a UIButton inside of an array which I would like to subclass to a SpringButton (https://github.com/MengTo/Spring). I tried this:

let springButton = playableCards[cardIndex] as! SpringButton

But I get this error:

Could not cast value of type 'UIButton' (0x1126bf120) to 'Spring.SpringButton' (0x10e6e62e8).

I do not want to create outlets or changing it in Storyboard. Is this a error from Swift, or an error from the pod itself?

Any help is welcome!

Edit:

var playableCards: [UIButton] = []
playableCards = self.allPlayableCardsViews[0].allSubviews.flatMap { $0 as? UIButton }

Where allPlayableCardsViews is just a regular UIView.

Upvotes: 0

Views: 259

Answers (1)

Paulw11
Paulw11

Reputation: 114836

If the class of the item in your storyboard scene is UIButton then the object is a UIButton and you can't simply downcast it as something else. If you want your buttons to be SpringButtons, and they are being created by a storyboard scene, then you need to set the custom class in the storyboard.

Since SpringButton is a subclass of UIButton you can pass a SpringButton anywhere a UIButton is expected. You can also downcast a variable of type UIButton to a SpringButton as long as the underlying object is a SpringButton. Conditional downcasts with as? are safer than forced downcasts as you have found.

Imagine you have a parking space. Vehicles can park in the space. Motorcycles and cars are both types (subclasses if you will) of vehicle, so either can park there. But whether a vehicle is a car or a motorcycle is determined when it is built. You can't simply convert a motorcycle to a car by saying so later, but this is what you are trying to do with your buttons.

Upvotes: 2

Related Questions