ホーム 暮らし [SwiftUI] #9 Implementing a Half-Modal

[SwiftUI] #9 Implementing a Half-Modal

三浦 拓海 三浦 拓海 • 更新: • 公開: • 読了約 4 分
目次

We will create a half-modal.

Standard modal

n220546a68d0e
import SwiftUI

struct ContentView: View 
    @State private var isModalView = false
    var body: some View 
        Button("button") 
            isModalView = true
        
        .sheet(isPresented: $isModalView) 
            ModalView()
        
    


struct ModalView: View 
    var body: some View 
        Text("This is modal view.")
    

In the code above, pressing the button labeled "button" displays a modal screen that covers the entire screen. This time, I want to display a modal screen that is half the size.

Half-modal

A half-modal is simple. You can complete it by just making a few small adjustments to the previous code.

        .sheet(isPresented: $isModalView) 
            ModalView()
                .presentationDetents([.medium])
        

Simply add the presentationDetents modifier and pass [.medium] as an argument to finish.

.medium is one of the elements of the PresentationDetent structure. PresentationDetent is a Hashable and Sendable structure that is defined as a standard in SwiftUI.

The reason why you need to pass it as an array even though it is just .medium is because there are cases where you might pass multiple elements here. For example, you can also pass [.medium, .large]. If you pass [.medium, .large], the user can drag to display the screen in full-screen mode in addition to the half-screen display. [.medium] does not allow for full-screen display.

同じカテゴリの記事

三浦 拓海
コンテンツディレクター 三浦 拓海
プロフィールを見る →

映画と連続ドラマの公開情報を追う担当。配給会社のプレスシートと公式サイトの発表日を確認したうえで執筆します。

おすすめの関連記事