SwiftUIで、要素を配置するときに、offset と position を使って位置を指定することができます。
Sponsor Link
目次
知りたいこと:position と offset に違いはあるか?
もちろん、違いはあるんでしょうけど、どんな影響があるのか調べてみました。
テキストを表示して調べてみました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import SwiftUI struct ContentView: View { var body: some View { Text("Hello, World!") .background(Color.red) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } |
offset
表示位置を移動させることができる modifier です。
Offset での移動後にもBackgroundを使って背景色を変えると効果がわかりやすいです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import SwiftUI struct ContentView: View { var body: some View { Text("Hello, World!") .background(Color.red) .offset(x: 100, y: 200) .background(Color.orange) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } |
offset の考察
Offset は、そこまでの結果の表示位置を変更することがわかります。ですので、そこまでに作成されたテキスト(Hello, World!)や背景色(赤)は移動して描画されますが、offset 後に指定された背景色(オレンジ)は、移動されずに残ります。
position
Positionで移動させてみましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import SwiftUI struct ContentView: View { var body: some View { Text("Hello, World!") .background(Color.red) .position(x: 120, y: 50) .background(Color.blue) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } |
position の考察
背景が青一色になることから、position は、与えられた領域をできる限り大きく使うことがわかります。
ですので、position 指定以降は、そのサイズを取得しても、テキストのサイズは取れないことになります。
position と offset を両方使ってみる: offset -> position
実際には、あまり使わないと思いますが、両方つかってどうなるかみてみました。
offset -> position の順で使ってみました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import SwiftUI struct ContentView: View { var body: some View { Text("Hello, World!") .background(Color.red) .offset(x: 100, y: 200) .background(Color.orange) .position(x: 120, y: 50) .background(Color.blue) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } |
offset -> position 順での考察
positionで位置指定されたところから、offsetされることがわかります。
position と offset を両方使ってみる: position -> offset
今度は、position 指定した後に、offset してみます。
position -> offset 順での考察
position が最初に適用されているため、背景色がオレンジ、青共に画面いっぱいに広がっています。
テキストとともに、画面いっぱいに作られたオレンジが、offset 指定で表示位置を変更され、その後背景を青にしていることが、わかります。
わかったこと:position は、利用可能領域を埋める
Position は利用可能領域を埋めて表示しますし、offset は、表示位置を移動させますが、表示領域を拡張することはしません。
このあたりの差異が、使い分けるときのポイントな気がします。
Sponsor Link