Several Ways to Center Views in SwiftUI
Centering a view within its parent view is a common requirement, and it is not difficult even for beginners in SwiftUI. There are many ways to achieve this goal in SwiftUI. This article will introduce some of these methods and explain the implementation principles, applicable scenarios, and precautions for each method.
Stay ahead with the latest updates and deep insights on Swift, SwiftUI, Core Data, and SwiftData. Subscribe to Fatbobman’s Swift Weekly to get exclusive articles, tips, and curated resources delivered straight to your inbox every week.
For even more valuable content and in-depth tutorials, visit my blog at fatbobman.com — your go-to destination for all things Swift and Apple development.
Requirement
Implement the style shown in the figure below: center a single-line Text
within a colored rectangle view.
Filler
Spacer
The most common and easiest solution is to use Spacer
.
var hello: some View {
Text("Hello…