Collaborative beamforming (CB) of a virtual antenna array (VAA) is an effective approach to enhance communication performance of UAV swarms. In this paper, the beam optimization problem for a UAV swarm-based VAA in the scenario that involves both target receivers and interception eavesdroppers is investigated. By jointly optimizing not only the positions and attitudes of the UAVs, but also the amplitude and phase weights of the signals emitted from the array elements, the desired beam is formed and the radiation power towards the target receivers is maximized. Taking into account the variations in the numbers of antenna array elements carried by UAVs in the heterogeneous UAV swarm, along with the constraints on the available transmit power and UAV flight performance, the optimization model is formulated. To improve computational efficiency, the optimization problem is decomposed into two subproblems: the static beamforming problem and the dynamic beamforming problem. A closed-form solution for the beamforming weight that satisfies power constraint is derived for the former problem. The Particle Swarm Optimization (PSO) algorithm is utilized in the latter problem to determine the positions and attitudes of the UAVs. Finally, numerical simulations are conducted to validate the effectiveness of the proposed algorithm. In addition, Monte Carlo simulation experiments confirm its compliance with real-time requirements and its ability to produce stable solutions.