This is not just a problem in Spain. Affordable housing is a problem in almost every Western metro, both in the US and in Europe. The problem is caused by the financialization of real estate. I know it's always been a bit of a financial asset, but the past 40 years have really seen this accelerate to pretty crazy levels. The issue, when you boil it down to the basics is: wealthy folks, development companies, overseas…
Is it not a supply and demand problem? Then the only rational solution to get prices down is to build more housing.
There are so many empty and decaying homes all over Europe, in Italy they sell houses for 1 Euro. Yes there's a catch but that catch is that you are supposed to renovate the house for a cost that ranges from 20K euros to 100K euros and this is still quite cheap considering that you end up with a proper house at a picturesque location.