Simple but useful Tips about SwiftUI for beginners
Tip 1:
Always apply .background() after setting .padding()
Here is an example,
Text("Hello")
.background(Color.blue)
.padding(.horizontal, 40)
.padding(.vertical, 20)
For the above snippet, I’ll get something like below
Same thing if we apply the tip,
Text("Hello")
.padding(.horizontal, 40)
.padding(.vertical, 20)
.background(Color.blue)
we will get,
Concept: Padding will add given area to the element. So, the First case applies the background colour then adding the padding area which is white in colour so we cannot see that. The second case, we have increased the area by applying the padding, then we are applying the background colour.
Tip 2:
Always apply .cornerRadius() after setting .background(Color.blue)
Example,
Text("Hello")
.padding(.horizontal, 40)
.padding(.vertical, 20)
.cornerRadius(9)
.background(Color.blue)
The output of the above snippet is,
You may think, Where is the corner radius? 🤔
Now, Apply the tip
Text("Hello")
.padding(.horizontal, 40)
.padding(.vertical, 20)
.background(Color.blue)
.cornerRadius(9)
Now, we got our corner radius.
Concept: .conerRadius() modifier will just crop out the corners of the element with given radius. In the first case, we have cropped the corners and applied background colour including the cropped area. In the second case, we have applied background then, applied the corner radius perfectly working.
Tip 3:
Want to get the screen width and height without Geometry Reader? use the snippet below,
let width = UIScreen.main.bounds.width
let height = UIScreen.main.bounds.height
Tip 4:
Rotate some view for a particular degree with .rotationEffect(.init(degrees:)) modifier.
Rectangle()
.fill(Color.red)
.frame(width: 100, height: 100)
.rotationEffect(.init(degrees: 45))
Tip 5:
Change view by applying .clipeShape() modifier
Rectangle()
.fill(Color.red)
.frame(width: 100, height: 200)
.clipShape(Capsule())
.rotationEffect(.init(degrees: 45))
.clipeShape(Capsule()) will change the rectangle’s shape to a capsule shape.
Tip 6:
Set text font size with .font(.system(size: 30)) modifier
HStack {
Text("Hello")
Text("World")
.font(.system(size: 30))
.bold()
}