1
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?

More than 1 year has passed since last update.

【SwiftUI】特定の条件でのみオーバーレイする

Last updated at Posted at 2023-01-21

はじめに

条件によってText("Hello, world!")にオーバーレイの有無を決定したいとします。

サンプルアプリ

Simulator Screen Recording - iPhone 14 Pro - 2023-01-21 at 21.35.26.gif

やりかた

ContentView
import SwiftUI

struct ContentView: View {
    @State var isShowBorder: Bool = false
    var body: some View {
        VStack(spacing: 50) {
            Toggle("", isOn: $isShowBorder)
                .labelsHidden()

            Text("Hello, world!")
                .padding(.init(top: 10, leading: 20, bottom: 10, trailing: 20))
                .overlay(isOverlay: isShowBorder) {
                    RoundedRectangle(cornerRadius: 10).stroke(style: .init(lineWidth: 3))
                }
        }
    }
}
View+
import SwiftUI

extension View {
    @ViewBuilder
    func overlay<T: View>(isOverlay: Bool, content: () -> T) -> some View {
        if isOverlay {
            self.overlay {
                content()
            }
        } else {
            self
        }
    }
}

ここで重要なのは@ViewBuilderです。

おわり

久しぶりにSwiftUIの記事を書きました

1
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
1
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?