The distinction is between providing services and providing software.
When iCloud scans stored files like Google Drive, nobody complains. It's understandable that risk adverse legal departments have come to the conclusion that doing such things is necessary, to avoid a company being in possession of trivially-discoverable CSAM. And from an individual security perspective, you should consider everything you upload unencrypted to be the subject of similar analysis.
If iOS were to encrypt all files before uploading, making any iCloud scanning mostly pointless, Apple would still not be running afoul of any law. Apple is making general software for end users, and encrypting files to upload would be doing the basic user diligence I alluded to. If users end up using the software to do bad things, those specific users are liable and not Apple.
As far as I am aware, there is no legal requirement for a software developer to modify their software to perform scanning of content it will process while being run by other people. But this is what is implied when you say that Apple is forced to do this by law.
Furthermore if this development was driven by iCloud worrying about legal liability from the combined system, then iCloud should be spun out into a separate company that cannot affect the development of the iOS software.