Several Ways to Center Views in SwiftUI

fatbobman ( 东坡肘子)
9 min readMar 17, 2023
Photo by Alexander Grey on Unsplash

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…

--

--

fatbobman ( 东坡肘子)
fatbobman ( 东坡肘子)

Written by fatbobman ( 东坡肘子)

Blogger | Sharing articles at https://fatbobman.com | Publisher of a weekly newsletter on Swift at http://weekly.fatbobman.com

No responses yet