0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ZStackの要素の配置時に便利なModifier

Last updated at Posted at 2024-12-11

概要

ZStackの時に便利なModifierを書いたので、新しいプロジェクトなどでコピペできるよう置いておきます

こんな感じのものがすでに公式から提供されていたらすみません

使い方

つけるだけ、特に複数のViewを異なる場所に寄せたい時に便利

ZStack {
    HogeView()
        .topLeading() // 左上に配置される

    HogeView()
        .topTrailing() // 右上に配置される
}

コード

import SwiftUI

public extension View {
    // 左上
    func topLeading() -> some View {
        self.modifier(TopLeadingAlignmentModifier())
    }

    // 右上
    func topTrailing() -> some View {
        self.modifier(TopTrailingAlignmentModifier())
    }

    // 左下
    func bottomLeading() -> some View {
        self.modifier(BottomLeadingAlignmentModifier())
    }

    // 右下
    func bottomTrailing() -> some View {
        self.modifier(BottomTrailingAlignmentModifier())
    }
}

struct TopLeadingAlignmentModifier: ViewModifier {
    func body(content: Content) -> some View {
        VStack(spacing: 0) {
            HStack(spacing: 0) {
                content
                Spacer()
            }
            Spacer()
        }
    }
}

struct TopTrailingAlignmentModifier: ViewModifier {
    func body(content: Content) -> some View {
        VStack(spacing: 0) {
            HStack(spacing: 0) {
                Spacer()
                content
            }
            Spacer()
        }
    }
}

struct BottomLeadingAlignmentModifier: ViewModifier {
    func body(content: Content) -> some View {
        VStack(spacing: 0) {
            Spacer()
            HStack(spacing: 0) {
                content
                Spacer()
            }
        }
    }
}

struct BottomTrailingAlignmentModifier: ViewModifier {
    func body(content: Content) -> some View {
        VStack(spacing: 0) {
            Spacer()
            HStack(spacing: 0) {
                Spacer()
                content
            }
        }
    }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?