NEW: Get your ticket for Hacking with Swift Live 2019! >>

< How to give a view a custom frame   How to color the padding around a view >

How to adjust the position of a view

All views have a natural position inside your hierarchy, but the offset() modifier lets you move them relative to that natural position.

Important: Using offset() will cause a view to be moved relative to its natural position, but won’t affect the position of other views. This means you can make one view overlap another when normally it would have been positioned next to it, which may not be what you want.

For example, in this VStack we can use offset() to move the second item down by 15 points so that it begins to overlap the third item:

VStack {
    Text("Home")
    Text("Options")
        .offset(y: 15)
    Text("Help")
}

You will commonly find that using padding() together with offset() gives you the result you’re looking for, as that moves one view around while also adjusting the views next to it to match.

For example, this will move the second item down by 15 points, but add 15 points of padding to its bottom edge so that it doesn’t overlap the text view below:

VStack {
    Text("Home")
    Text("Options")
        .offset(y: 15)
        .padding(.bottom, 15)
    Text("Help")
}

HACKING WITH SWIFT LIVE This July is a new two-day event where you'll be inspired by great speakers on day one then learn all the amazing new features from WWDC on day two – click here for more information and tickets.

< How to give a view a custom frame   How to color the padding around a view >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 5.0/5

Click here to visit the Hacking with Swift store >>