Recent developments in unmanned aerial vehicles (UAVs) have led to the introduction of a wide variety of innovative applications, especially in the Mobile Edge Computing (MEC) field. UAV swarms are suggested as a promising solution to cope with the issues that may arise when connecting Internet of Things (IoT) applications to a fog platform. We are interested in a crucial aspect of designing a swarm of UAVs in this work, which is the coordination of swarm agents in complicated and unknown environments. Centralized leader–follower formations are one of the most prevalent architectural designs in the literature. In the event of a failed leader, however, the entire mission is canceled. This paper proposes a framework to enable the use of UAVs under different MEC architectures, overcomes the drawbacks of centralized architectures, and improves their overall performance. The most significant contribution of this research is the combination of distributed formation control, online leader election, and collaborative obstacle avoidance. For the initial phase, the optimal path between departure and arrival points is generated, avoiding obstacles and agent collisions. Next, a quaternion-based sliding mode controller is designed for formation control and trajectory tracking. Moreover, in the event of a failed leader, the leader election phase allows agents to select the most qualified leader for the formation. Multiple possible scenarios simulating real-time applications are used to evaluate the framework. The obtained results demonstrate the capability of UAVs to adapt to different MEC architectures under different constraints. Lastly, a comparison is made with existing structures to demonstrate the effectiveness, safety, and durability of the designed framework.